Search code examples
bashcut

Cut is working unexpected?


I want to cut a line into fields with custom delimeter:

echo "field1   field2    field3" | cut -d\  -f2

I expect field2 to show in result, but I get nothing. How can I split it with cut?


Solution

  • The problem is, that there's more than one space. cut(1) doesn't collapse the delimiter. It will split on the first delimiter encountered.

    POSIX has this to say about it (emphasis mine):

    • -f list
      Cut based on a list of fields, assumed to be separated in the file by a delimiter character (see -d). Each selected field shall be output. Output fields shall be separated by a single occurrence of the field delimiter character. Lines with no field delimiters shall be passed through intact, unless -s is specified. It shall not be an error to select fields not present in the input line.

    Solutions:

    1. If you're on FreeBSD, use -w; this will split on whitespace (while very useful, this is non-standard; and not portable to GNU cut)
    2. Use -f 4
    3. use awk(1): echo "field1 field2 field3" | awk '{print $2}'
    4. Use tr(1) to collapse all spaces to a single space: echo "field1 field2 field3" | tr -s \ | cut -d\ -f2