1

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?

danbst
  • 3,363
  • 18
  • 38

2 Answers2

6

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
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
  • I'm aware of `awk` (as suggested in http://stackoverflow.com/questions/3005627/bash-nth-word-in-a-string), but I'm frustrated that top answer there doesn't work. – danbst Aug 08 '14 at 18:49
  • @danbst This actually makes sense :-) I've updated my answer with some extra explanation on what's going on – Martin Tournoij Aug 08 '14 at 18:52
1

You can use awk:

echo "field1   field2    field3" | awk '{print $2}'
field2

since cut doesn't handle multiple delimiters correctly.

Or else use tr to truncate multiple spaces into one first:

echo "field1   field2    field3" | tr -s ' ' | cut -d ' ' -f2
field2
anubhava
  • 761,203
  • 64
  • 569
  • 643