Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace line after match

Tags:

bash

sed

awk

Given this file

$ cat foo.txt
AAA
111
BBB
222
CCC
333

I would like to replace the first line after BBB with 999. I came up with this command

awk '/BBB/ {f=1; print; next} f {$1=999; f=0} 1' foo.txt

but I am curious to any shorter commands with either awk or sed.

like image 385
Zombo Avatar asked Nov 30 '22 02:11

Zombo


2 Answers

This might work for you (GNU sed)

sed '/BBB/!b;n;c999' file

If a line contains BBB, print that line and then change the following line to 999.

!b negates the previous address (regexp) and breaks out of any processing, ending the sed commands, n prints the current line and then reads the next into the pattern space, c changes the current line to the string following the command.

like image 88
potong Avatar answered Dec 04 '22 05:12

potong


This is some shorter:

awk 'f{$0="999";f=0}/BBB/{f=1}1' file

f {$0="999";f=0} if f is true, set line to 999 and f to 0
/BBB/ {f=1} if pattern match set f to 1
1 print all lines, since 1 is always true.

like image 40
Jotne Avatar answered Dec 04 '22 03:12

Jotne