awk help!

Hey I've just been recently introduced to bash.... well actually unix let alone bash. I'm having a problem with an awk statement:

unit1=$(grep "$cap1" convert.table | awk -F"\t" '{$NF="" ; print $0}' | awk -F"\t" '{$NF="" ; print $0}' | awk -F" " '{if (NF == 4) print $1, $2, $3} ; {if (NF == 3) {print $1, $2} ; {if (NF == 2 ) print $2}')

The problem lies in the third awk statement; I'm trying to see how many fields exist on the current line and print the data accordingly. If theres 4 fields of data I just want the first 3 fields to be printed, etc.

Any help would be greatly appreciated, thanks :slight_smile: :b:

Try the following for the third awk statement:

 
awk -F" " '{ if (NF == 4) print $1, $2, $3; if (NF == 3) print $1, $2; if (NF == 2) print $2 }'

I've tried that already and got the following message:

awk: (FILENAME=- FNR=1) fatal: division by zero attempted

?? I'm really lost here because even if i shave the last two "if" statements off, I still get the error but can't seem to figure out the problem :confused:

Give a sample of the input file and the output you desire, perhaps you can do the job with one awk statement.

Regards

You didn't say what the problem was. This code looks OK to me:

# echo 123 | awk '{if(NF==2) print};{if(NF==1)print}'
123
# echo 123 456 | awk '{if(NF==2) print};{if(NF==1)print}'
123 456
# echo 123 456 789| awk '{if(NF==2) print};{if(NF==1)print}'

It looks like you have tab-delimited data AND space-delimited data, and therefore what you're trying is:

"If the line ends in two consecutive tabs (making the last field and next-to-last field empty) then parse the first field by spaces. With 4 words, print the first three; with 3 words, print the first two; with two words, print only the last."

That's a really weird way to parse. Maybe you could post some same input data and a sample of your desired output?

And yes, you should be able to this this with one awk statement. You don't even need the grep:

awk -v PAT="$cap1" '{if ($0~PAT) print}' convert.table
   or
awk '/'$cap1'/{print}' convert.table

:cool: Ok it works now, the problem was the second awk statement... since it gets rid of the second last field, the grep wasn't finding a pattern (because the pattern lied in the second last field) so I just tweaked it like so:

unit1=$(grep "$convert1" /home/ashamon/asgm2/chinballz/convert.table | awk -F"\t" '{$NF="";print $0}' | awk -F" " '{ if (NF == 5) print $4 ; if (NF == 4) print $3 ; if (NF == 3) print $2 }' 2> /dev/null)

Thanks alot guys, I really appreciate the help, and your responses were pretty quick :b: have a good one :stuck_out_tongue: