0

I am searching for a pattern in a field of my file with several rows. If the pattern is present I would like to output that row. However, if the pattern is not present at all I would like to output something like "missing".

awk '{if($2=="123456"){print $0} else {print "not present"} }' file.txt

(this does not work due to line by line output)

My problem is the line by line output here. There is one output per line, but I want either the row that matches the pattern or the term "missing" (only once).

I appreciate every kind of help! I tried several approaches including grep, if else, loops, but nothing works as I want.

anubhava
  • 761,203
  • 64
  • 569
  • 643
PsoAD
  • 25
  • 5

1 Answers1

2

Reading between the lines I think you want something like this:

awk '$2 == "123456" { print; f = 1 } END { if (!f) print "missing" }' file

This prints the line when the second field matches and sets a flag f. Once the file is processed, if the flag is still unset, the message is printed.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141