1824976 Members
3497 Online
109678 Solutions
New Discussion юеВ

Awk script help

 
SOLVED
Go to solution
Shannon_1
Occasional Advisor

Awk script help

I am trying to write an awk script with multiple conditional statements and have some syntax wrong somewhere. My record has 3 columns of data. I want to print some stuff based on the second column's contents. So code is something like:



{
if ($2="ABC")
{printf $1}
if ($2="BCD")
{printf $3}
} etc.....



This code is executing every print statement nomatter what column 2 has in it.

What am i missing?
4 REPLIES 4
Stuart Browne
Honored Contributor
Solution

Re: Awk script help

Not enough ='s signs. You're assing "ABC" to $2 etc. etc.

if ($2 == "ABC") { print $1 }
else if ($2 == "BCD") { print $3 }

etc. etc.

NOTE: I highly recomend you use 'else if'.. saves a fair bit of processing, especially if you have a number of possibilities, unless you throw a 'next' in there somewhere.
One long-haired git at your service...
Leif Halvarsson_2
Honored Contributor

Re: Awk script help

Hi

it should be == not =.

Have you tried without if ?

$2=="ABC" {printf $1}
$2=="BCD" {printf $3}


Juan M Leon
Trusted Contributor

Re: Awk script help

Hi you can try the follwing is easy:

awk ' $2 ~ /ABC/ {print $1} $2 ~ /BCD/ {print $3}' filename

I hope it helps.

Juan
Gordon  Morrison
Trusted Contributor

Re: Awk script help

Why be AWKward?
As you have discovered, awk syntax is a pig.
In scripts, I get around it by using functions. This means more typing, but is much easier to code (and read)
e.g.
Say the line you want to extract fields from is in a variable called "myline"...

#!/usr/bin/ksh
myfunc()
{
if [[ $2 = "ABC" ]] ; then
echo $1
elif [[ $2 = "DEF" ]] ; then
echo $3
# etc...
fi
}

#Main code
myline="ABC DEF GHI JKL MNO PQR STU VWX YZ"
myfunc $myline

The above will echo GHI to the screen.
What does this button do?