1

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.

Jerry
  • 68,613
  • 12
  • 97
  • 138
N Klosterman
  • 1,161
  • 13
  • 23

2 Answers2

1

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
anubhava
  • 713,503
  • 59
  • 514
  • 593
0

A long awk to get the correct output

awk '{for (i=1;i<=NF;i++) {if ($i=="three") f=1;if (f) printf "%s ",$i}print ""}' file
three four five four three two one
Jotne
  • 39,326
  • 11
  • 49
  • 54