-3

Let's say i have a file with below content.

ok     yes    bad
ok     yes    good
ok     yes    bad
ok     yes    good
ok     yes    bad
ok     yes    good

I need to write a shell script or awk program to search the whole 3rd column and if the whole column is good then print as "Everthing looks good" and incase if it finds anyone bad then print as "Things are not okay"

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
suru1432002
  • 143
  • 2
  • 8

3 Answers3

2

Do it with a simple awk one-liner condition:

awk 'BEGIN {ok=1;} $3=="bad" { ok=0 } END { if (ok==0) {print "Things are not okay"} else { print "Everything looks good"} }' yourfile

BEGIN block initializes ok to 1 before file parsing starts. Default: all is ok unless bad is found.

Your file has natural space/tab separation, no need to tweak awk field separator: $3 is directly the third field that we need. Just test if meets bad somewhere, and if so, cancel the ok flag.

END block is executed at the end of the file. Check ok and print relevant message.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0
$ awk '$3=="bad"{f=1; exit} END{print (f ? "Things are not OK" : "Everything looks good")}' file
Things are not OK

The above sets a flag and exists the main work loop (NOTE: exit doesn't exit the program, just the implicit loop that's reading the input, so then it takes you to the END section) the first time it finds "bad" so it's as efficient as possible and then in the END section it uses a ternary expression to print the relevant message based on that flag being set or not.

If you will be doing any text manipulation ever in your life, read the book Effective Awk Programming, 4th Edition by Arnold Robbins to learn how to do it concisely, efficiently, robustly, and portably.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

You could do:

awk '$3=="bad"{bad++} END { if (bad>0) print bad " bads found"; else print "all goods!"}' file
dawg
  • 98,345
  • 23
  • 131
  • 206