Hi ,
Does awk have any "if" and "else" syntax ?
Can somebody show me an example > ?
Hi ,
Does awk have any "if" and "else" syntax ?
Can somebody show me an example > ?
Hi All,
I have got a problem here.
Input file
aa bb cc 100
aa bb xx 200
using the below to invoke
nawk -f check_awk inputfile
where check_awk is
if ($1 == "aa" && $3 == "xx") {SB = $4} else {SB = 0};
END{
printf("%5s\n",SB)
}
What i am getting is 0 and not 200. Why ???
Only if aa bb xx 200 is last line of the file , you will get 200.
Remove else part
if ($1 == "aa" && $3 == "xx") {SB = $4}
END{
printf("%5s\n",SB)
}
I put the following in the check_awk file and it works for me - Make sure u don't put the "if" in the BEGIN block. Also check the exact syntax.
{ if ($1 == "aa" && $3 == "xx") { SB = $4 } else { SB = 0} }
END{ printf("%5s\n",SB) }
Hi All,
It seems that when i add the 2nd statement, the i didn;t get the value that i want.
{if ($1 == "aa" && $3 == "xx") {SB = $4} else {SB = 0};
if ($1 == "aa" && $3 == "cc") {SB1 = $4} else {SB1 = 0};
}
END{
printf("%5s %5s\n",SB,SB1);
}
I get 0 instead of 100 for SB1. Why ?
The first record sets SB1 to 100. Then the second record sets SB1 to 0.
for your input
aa bb cc 100
aa bb xx 200
the output
200 0
is exact
because for each and every line 2 if statements are executed and the value would be reset to 0
and the output is correct!
Hi matrixmadhan,
But how do i get the code to output what i desire, which is 200 for SB and 100 for SB1 ?
check if the value has been assigned already
awk '{if ($1 == "aa" && $3 == "xx") { SB = $4 } else { if ( !SB ) SB = 0}; if ($1 == "aa" && $3 == "cc") { SB1 = $4 } else { if (!SB1) SB1 = 0}; } END{ printf("%5s %5s\n",SB,SB1);}' filename
hi matrix,
thanks it works!!
But can you tell me what does this syntax !SB means ?
negate operator check,
check if the value of SB is already set or not!
Thanks you so much.But I don not know what dose this mean -F