Monday, April 2, 2018

regex - Replace everything up to first string occurrence





I'm trying to perform a substitution of the everything up to and including the first occurrence of a string but am failing.



Say I have the following string:



one two three four five four three two one



I want to get



three four five four three two one


but with



sed 's/.*three//'



I end up with



two one 


I've tried other variations with .* -> (.*$) and (.*?) to no avail.



I've seen how to replace the first occurrence http://techteam.wordpress.com/2010/09/14/how-to-replace-the-first-occurrence-only-of-a-string-match-in-a-file-using-sed/ but not everything up to that first occurrence.



Answer



Since sed doesn't support lazy quantifier ?, you can use this sed:



echo "$s" | sed 's/.*two \(three\)/\1/'
three four five four three two one


OR using perl:



echo "$s" | perl -pe 's/.*?(three)/\1/'

three four five four three two one

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...