Home > database >  sed: search for a pattern after a particular line containing a keyword
sed: search for a pattern after a particular line containing a keyword

Time:10-09

input file:

new file
myString
abc
myString
xyz
pattern
file txt
myString
almost the end of file
myString
end of file

The input file contains multiple occurrences of myString throughout the entire file but I need to replace only the first occurrence of myString that occurs after another pattern pattern.

Also, there are no specific number of lines between pattern and first occurrence of myString.

desired output:

new file
myString
abc
myString
xyz
pattern
file txt
replacement_pattern
almost the end of file
myString
end of file

I want to do this task using sed, if possible

CodePudding user response:

The simple would be just:

/pattern/,/myString/s/myString/replacement_pattern/

For the first and only first myString in file I think there should be something simple, but I ended up with:

/pattern/,${ x; /myString/!{ x; //{ h; s//replacement_pattern/}; x}; x}'

A bit shorter:

/pattern/,${ /myString/{ x; //!{ g; s//replacement_pattern/; x}; x} }

CodePudding user response:

This might work for you (GNU sed):

sed '/pattern/{:a;N;s/myString/myReplacement/;Ta}' file

Gather up lines after finding one that contains pattern and replace the first match with a replacement string.

Alternative:

sed '/pattern/{:a;N;/myString/!ba;s//myReplacement/}' file

Same idea but using traditional sed commands rather that GNU specific.

  • Related