Extracting data with awk when some lines have empty/missing values

awkgawkgrepsedtext processing

I have a sample as shown here:

input.txt

   USERS        position   ref   rslt   
    usr1                    X     B   
    usr2          2980            C   
    usr3          3323      P      
    usr4                          A  
    usr5          5251      U      
    usr6          9990            A
    usr7          10345     T     

I need to print "rslt" column and corresponding "USERS", output file should be like this:

output.txt

  USERS     rslt   
   usr1       B   
   usr2       C       
   usr4       A
   usr6       A 

I tried to use awkcommand but it didn't work. Note that, all black position of the table is filled with spaces (No. of spaces is different in each row)

Best Answer

In this case, one possible solution is to provide the widths of the fields in the beginning section:

awk 'BEGIN {FIELDWIDTHS = "16 11 6 7"} 
    $4 ~/[^ ]/ {print $1 $4}' 

Fieldwidths may be counted by hand, but for complex headers I like to start with

 head -1 f | grep -Po '.*? (?=\S|$)' | awk '{print length}'

UPDATE: ... or in order to deal with initial and final spaces in the header:

 head -1 f | grep -Po '(^ *|\S).*?( (?=\S)|$)' | awk '{print length}'
Related Question