Search code examples
bashperlawksed

How to replace line in a file after htting a particular line in bash


So I have a simple use case, I have a file like

line_1
anything
anything
anything
aaa
line_2
line_3
anything
anything
anything
aaa
anything
anything
line_4
aaa

Now I have to replace the first aaa which comes after line_3.

Output-

line_1
anything
anything
anything
aaa
line_2
line_3
anything
anything
anything
YES REPLACE THIS
anything
anything
line_4
aaa

I was able to replace anything on the very next line using-

sed -i '/line_3/{n; s/aaa/YES REPLACE THIS/}' file.txt

But aaa is not of the next line, I do not know after how many lines it occurs, any solution using sed, awk or anything bash related will work, any help will be appreciated.


Solution

  • Set a flag once it sees line_3, unset it once it finds and replaces the pattern

    perl -wpe'if ($on) { $on = 0 if s/aaa/XXX/ }; $on = 1 if /^line_3$/' file
    

    This only prints the resulting lines to screen. If you want ot change the file ("in-place") add -i switch (perl -i -wpe'...'), or better -i.bak to keep a backup, too.