moadeep
moadeep

Reputation: 4098

Awk coping when column is occassionly empty

I have output from a foreach loop in the form:

ABC123603LP    44Bq    AAAA       
ABC123603P     3BU     AAAA       
ABC123603ZZP           AAAA       
ABC123604DP    3BU     BBBB     
ABC123604LP    44Bq    BBBB      
ABC123605AP    4q      CCCC    
ABC123605DP    33BGU   CCCC    
ABC123606AP    35Bjq   DDDD     
ABC123606DP    4B      DDDD

From this I wish to print columns 1 and 2 to the terminal with

echo ... | awk '{print $1, $2}'

However the third row and others prints ABC123603ZZP AAAA as the second column is blank in this case. How do I get around this?

Upvotes: 3

Views: 908

Answers (3)

perreal
perreal

Reputation: 97938

You can use sed instead:

echo ... | sed 's/\(A[^ ]*[\t ]*\)\([^ \t]*[0-9][^ \t]*\)*.*/\1 \2/'

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246764

One technique to remove the last column is to make awk think there are 1 fewer fields:

awk -v OFS='\t' '{NF--; print}'

Upvotes: 0

Chris Seymour
Chris Seymour

Reputation: 85775

Check the number of field before you print:

$ awk 'BEGIN {OFS="\t"}{ if (NF==2)  print $1; else print $1, $2}' file
ABC123603LP     44Bq
ABC123603P      3BU
ABC123603ZZP
ABC123604DP     3BU
ABC123604LP     44Bq
ABC123605AP     4q
ABC123605DP     33BGU
ABC123606AP     35Bjq
ABC123606DP     4B

Upvotes: 2

Related Questions