Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

An error in if else loop, your opinion 2

Status
Not open for further replies.

gargamel100

Technical User
Oct 25, 2006
31
CZ
Hi all,
using code bellow I want to check if $21=="1" and $9=="2222". If this is true then print 2222, and value for a.

awk -F"|" '
$21 == "1" && $9 == "2222" {a=a+1}

END {print " 2222 ", a}'

But in some cases a is equal 0 and in that case
END {print " 2222 ", a} will print just 2222, like
2222
but I wish in this case (when a is zero) to print zero and got output like
2222 0
and so on.
I tried make this using
END {print " 2222 ", if (a==0) print a else print "0"}
but I got an error like

syntax error at or near if

I really do not know what I made wrong in this case, and if someone can see my mistake, please write it down.

Regards

Gargamel100
 
I mean

END {print " 2222 ", if (a!=0) print a else print "0"}
 
The correct syntax would have been:

[tt]END {printf " 2222 " ; if (a!=0) { print a } else { print "0" } }[/tt]

But obviously a+0 is much shorter.

Annihilannic.
 
this works ok
END {print " 2222 "; if(a!=0) {print a} else {print "0"} }
and I got output like

2222
0
how make it to be in same row like

2222 0
I tried using "\t" and got like
2222
"empty" 0

but I need this in form
2222 0

regards
 
You didn't notice the "printf".

But personally, I would just go to your original solution and change it to:

[tt]END {print " 2222 ", a+0}[/tt]

Annihilannic.
 
Hi

A short explanation :
Code:
END {print "  2222 "[red][b],[/b][/red]  if (a!=0) print a else print "0"}
[red]here is the error --^[/red]
There should be a semicolon ( ; ) th separate the two instructions.

Follow Annihilannic's suggestion, this is just as an idea. Is what you tried to do, just shorter :
Code:
END {print "  2222 ", [highlight #eee]a?a:0[/highlight]}

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top