Search code examples
cut

How to filter empty line with a 'cut' command?


I have a tab delimited file with a few fields:

f1    f2   f3 
a     b    c
a     c     
d     e    
f     g    a

I want to extract the 3rd column with a 'cut'command:

cut -f3 t

This works. However, how can I filter the empty line in the output? As it can be seen, the 2nd and 3rd lines are empty after they are extracted.


Solution

  • To remove empty output:

    $ cut -f3 file | grep .
    f3
    c
    a
    

    Or:

    $ awk -F'\t' '$3 {print $3}' file
    f3
    c
    a
    

    To replace the missing output with a filler:

    $ awk -F'\t' '{if ($3) print $3; else print "FILL"}' file
    f3
    c
    FILL
    FILL
    a
    

    Or, for people who like the more compact ternary statement:

    $ awk -F'\t' '{print ($3?$3:"FILL")}' file
    f3
    c
    FILL
    FILL
    a
    

    Example with multiple words in field 3

    $ cat file2
    f1      f2      f3
    f       g       a b c d
    $ cut -f3 file2 | grep .
    f3
    a b c d
    $ awk -F'\t' '$3 {print $3}' file2
    f3
    a b c d