Issue
Is there a way to replace the following two lines after a match is found using sed?
I have a file
#ABC
oneSize=bar
twoSize=bar
threeSize=foo
But I would like to replace the two immediate lines once the pattern #ABC
is matched so that it becomes
#ABC
oneSize=foo
twoSize=foo
threeSize=foo
I'm able to do
gsed '/^#ABC/{n;s/Size=bar/Size=foo/}' file
But it only changes the line twoSize
not oneSize
Is there a way to get it to change both oneSize and twoSize
Solution
gnu and some other sed versions allow you to grab a range using relative number so you can simply use:
sed -E '/^#ABC$/,+2 s/(Size=)bar/\1foo/' file
#ABC
oneSize=foo
twoSize=foo
threeSize=foo
Command details:
/^#ABC$/,+2
Match range from pattern#ABC
to next 2 liness/(Size=)bar/\1foo/
: MatchSize=bar
and replace withSize=foo
, using a capture group to avoid repeat of same String in search and substitution
You may also consider awk
to avoid repeating pattern and replacements N times if you have to replace N lines after matching pattern:
awk 'n-- {sub(/Size=bar/, "Size=foo")} /^#ABC$/ {n=2} 1' file
#ABC
oneSize=foo
twoSize=foo
threeSize=foo
Answered By - anubhava Answer Checked By - Clifford M. (WPSolving Volunteer)