cutgnu-coreutils

Is it a bug in the UNIX cut command that when selecting a specific field with a line with no delimiters, it returns the whole line?


I found this behavior of coreutils utility cut a bit weird

echo "
one,line1
two,line2
three
four,line4
" | cut -d ',' -f1

, got expected result:

one
two
three
four

But:

echo "
one,line1
two,line2
three
four,line4
" | cut -d ',' -f2

, gives outputs:

line1
line2
three
line4

I would expect 3rd line to be empty. Are my expectations wrong?


Solution

  • No, this is not a bug. From the manpage for the -f option:

    Select only these fields; also print any line that contains no delimiter character, unless the -s option is specified

    Since your third line has no delimiter, then it prints the whole line.

    If you add -s, you will get this output:

    line1
    line2
    line4
    

    If you add a delimiter to your third line at the end, like this

    echo "
    one,line1
    two,line2
    three,
    four,line4
    " | cut -d ',' -f2
    

    Then you will get this:

    line1
    line2
    
    line4