user3040797
user3040797

Reputation: 55

How to validate a contents of a file using awk command?

I have a file abc.txt with contents as :

8503 C
8501 C
8500 C

I want to validate the contents of the file in a such a way that:

For 8503 - the value has to be "C"
if yes then success
else Fail

It should repeat for all the contents in the file

ie. suppose if the file contains:

8503 E
8501 C
8500 C

Now 8503 has value as "E" then it is a failure. 8501 has value as "C" it is a success

How would I do it using shell script?


I tried the below command :

awk -F ' ' '$2 != "C" { echo "Value is not C for happy path" }' < /tmp/abc.data

but it gives me a blank output without the echo being displayed.

I want to see if the second column of the file has any value apart from "C" then it is a failure.

Any input is appreciated.

Thanks,

Upvotes: 1

Views: 1476

Answers (2)

xhienne
xhienne

Reputation: 6144

Just to help you with your awk script: your mistake is to use echo which is not a valid awk command. Use print instead:

awk '$2 != "C" { print "Value is not C for happy path" }' < /tmp/abc.data

(I removed the -F option which is not necessary: whitespace-separated fields is the default)

However, as stated by Walter in comment, a mere grep command seems to be enough in your case (with GNU sed here to add a header line):

grep E$ /tmp/abc.data | sed '1i Error lines:'

Upvotes: 0

JNevill
JNevill

Reputation: 50273

If you are wanting to check to see if there are any values in column 2 that aren't "C" which will cause a "fail" then:

 awk '$2!="C"{e=1;exit}END{print e?"fail":"success"}'

Upvotes: 2

Related Questions