Avinash Raj
Avinash Raj

Reputation: 174706

How to use if else in awk?

I have a text file and it's contents are like below,

foo.txt

firefox:
Installed: 24.0+build1-0ubuntu1
Candidate: 24.0+build1-0ubuntu1

I want to print the first field in the first line if the value of Installed and the Candidate are not same.If it's same then empty output is enough.

I tried,

cat foo.txt | awk '$1~/^Installed:/ {var=$2;next} $1~/^Candidate:/ {var1=$2;next} NR==1 {pkg=$1} {if(var != var1) { print pkg;} }'

But it displays nothing.It would be better if you provide an awk solution.

Upvotes: 1

Views: 237

Answers (1)

Ed Morton
Ed Morton

Reputation: 203502

You were close:

$ cat foo.txt
firefox:
Installed: 24.0+build1-0foo
Candidate: 24.0+build1-0bar

$ awk '$1~/^Installed:/ {var=$2;next} $1~/^Candidate:/ {var1=$2;next} NR==1 {pkg=$1} END {if(var != var1) { print pkg;} }' foo.txt
firefox:

Upvotes: 1

Related Questions