leetbacoon
leetbacoon

Reputation: 1249

sed remove up to a certain point, including the pattern itself

We have a string like the following:

ash oak brock misty oak oak james oak jesse misty

We need to remove everything up to the nth instance of oak in the string above and also remove the pattern itself.

So, sed with 1 would show:

 brock misty oak oak james oak jesse misty

sed with 2 would show:

 oak james oak jesse misty

sed with 3 would show:

 james oak jesse misty

sed with 4 would show:

 jesse misty

We use BSD sed but also can use GNU sed. Thanks

We tried sed $number',/^.*oak/{s/oak//}' but this didnt work

Upvotes: 2

Views: 255

Answers (2)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed 'H;g;s/\n//g;s/oak/\n/2;/.*\n/{s///;:a;n;ba};d' file

Append the current line to the hold space and then replace the current line by the contents of the hold space. Remove all newlines and replace the occurrence of the desire string by a newline. If the current line contains a newline, remove everything from the start of the current line up to and including the introduced newline and then fetch and print the remainder of the file. Otherwise delete the current line and repeat.

Upvotes: 1

anubhava
anubhava

Reputation: 784958

sed is not the right tool for this because there is no support for lazy quantifier in BRE or ERE.

As an alternative, you may use perl with more robust regex engine:

$> s='ash oak brock misty oak oak james oak jesse misty'

$> perl -pe 's/^(.*?\boak\b){2}\h*//' <<< "$s"
oak james oak jesse misty

$> perl -pe 's/^(.*?\boak\b){1}\h*//' <<< "$s"
brock misty oak oak james oak jesse misty

$> perl -pe 's/^(.*?\boak\b){3}\h*//' <<< "$s"
james oak jesse misty

Upvotes: 1

Related Questions