0

given file test and its content:

bcd://dfl
sf

I would like to append extra information to the line having certain content (starting with bcd) While the following script works

awk '/bcd*/ {print $0", extra information"} ' test > test.old && mv test.old test

it removes the non matching lines. (sf)

Is it possible to preserve them in the output file?

rok
  • 9,403
  • 17
  • 70
  • 126
  • 2
    Append `", extra information"` to `$0` and output with `1`after `}`. Also fix that `/bcd*/`, it matches any string with `bc` in it. You probably meant `/^bcd.*/` but `/^bcd/` suffices. – James Brown Apr 23 '17 at 16:03
  • 2
    Add `next` to the action block and add something of truth to cause printing after to default print: `awk '/^bcd/ {print $0", extra information"; next} 1'` – dawg Apr 23 '17 at 16:16

2 Answers2

3

As discussed over in the comments appending a {..}1 at the end will solve your problem,

awk '/^bcd/ {print $0", extra information"; next} 1' file

because the /<pattern>/{<action>} is applied to the lines only matching the <pattern>, the other lines are just printed as-is, {..}1 is a always-true-no-matter-what condition to print lines.

Inian
  • 80,270
  • 14
  • 142
  • 161
2
awk '/^bcd/ {$0 = $0 ", extra information"} 1' test
Ed Morton
  • 188,023
  • 17
  • 78
  • 185