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
  • 70,495
  • 13
  • 100
  • 144
N Klosterman
  • 1,231
  • 14
  • 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
  • 761,203
  • 64
  • 569
  • 643
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
  • 40,548
  • 12
  • 51
  • 55