How to loop over multiple values of a field with awk in bash?

Viewed 188

My dataset looks like this:

lastname|name|hash
A|B|C
D|E|
G|H|I J

I need the data in this format (preferably with awk) in bash.

{C}% B A
{I}% H G
{J}% H G

In words: Only if there is a value for the third column (hash) I want to output. There can be 1-n values in the third column (hash) and for each value the output should be like:

{hash}% name lastname

1 Answers
BEGIN { 
    FS="|"
}

NR>1 && NF==3 {
    split($3, a, " ")
    for (i=1;i in a;i++) printf("{%s}%% %s %s\n", a[i], $2, $1)
}

I think the above awk is self explanatory enough. To print the literal % with printf we have to escape it with %%. Testing:

> awk -f tst.awk file
{C}% B A
{I}% H G
{J}% H G
Related