5

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.

Zombo
  • 1
  • 62
  • 391
  • 407
  • 1
    Just remember that brevity isn't itself a desirable quality of software, conciseness (i.e. brevity with clarity) is. – Ed Morton Dec 09 '13 at 19:41

6 Answers6

9

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.

miken32
  • 42,008
  • 16
  • 111
  • 154
potong
  • 55,640
  • 6
  • 51
  • 83
6

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.

Jotne
  • 40,548
  • 12
  • 51
  • 55
  • `1 print all lines, since 1 is always true`. In fact it is a bit longer "1 prints all lines, since it is evaluated as true and the default action for "true" in `awk` is to `{print $0}`". Also, +1, I came up with the same solution when trying to squeeze the one-liner. – fedorqui Dec 09 '13 at 09:18
5

can use sed also, it's shorter

sed '/BBB/{n;s/.*/999/}'
Zombo
  • 1
  • 62
  • 391
  • 407
ray
  • 4,109
  • 1
  • 17
  • 12
3
$ awk '{print (f?999:$0); f=0} /BBB/{f=1}' file    
AAA
111
BBB
999
CCC
333
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
2
awk '/BBB/{print;getline;$0="999"}1' your_file
Vijay
  • 65,327
  • 90
  • 227
  • 319
-1
sed 's/\(BBB\)/\1\
999/'

works on mac

toph
  • 190
  • 1
  • 4