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
?
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:
-w
; this will split on whitespace (while very useful, this is non-standard; and not portable to GNU cut)-f 4
awk(1)
: echo "field1 field2 field3" | awk '{print $2}'
tr(1)
to collapse all spaces to a single space: echo "field1 field2 field3" | tr -s \ | cut -d\ -f2