awk condition

Hi Gurus,

one of my current script, there is awk statement as below:

 
awk  '{a[$1]=a[$1]?a[$1]" "$3:$3}END{for (i in a) print i,a}'

I don't understand what's "{a[$1]=a[$1]?a[$1]" "$3:$3}" mean?

can anybody give me a brief explaination.

thanks in advance.

That's what they call "conditional assignment", it's using "?" and ":" to separate the TRUE and FALSE branch:

a[$1]=      assignment target
a[$1]       logical condition (empty or 0: FALSE; any other value: TRUE)
?           starts TRUE branch
a[$1]" "$3  concatenation of two strings
:           starts FALSE branch
$3          single simple string

man awk is your friend!

1 Like

Hello Ken6503,

Following is the explaination.

a[$1]=a[$1]?a[$1]" "$3:$3
It means we are creating a array whose index is value of $1 and if value of $1 is repeating in the further then we are concatinating the values of all $1 into a single index

Let's say we have a file as follows.

cat test35
Singh   1       Ravinder        cool
Prince  2       Gurmeet         hot
Singh   3       Tinki           Handome

then to take all Singh and Prince(which is $1's value) into a single row we will use the code as follows and get the output as follows.

awk  '{a[$1]=a[$1]?a[$1]" "$3:$3}END{for (i in a) print i,a}' test35
Prince Gurmeet
Singh Ravinder Tinki

Hope this helps.

Thanks,
R. Singh

1 Like

Thanks RudiC,

the clear of your explaination likes crystal ball.

:b:

---------- Post updated at 12:18 PM ---------- Previous update was at 10:06 AM ----------

Thanks for your explaination R. Singh.