Use space as a delimiter with cut command

Viewed 394319

I want to use space as a delimiter with the cut command.

What syntax can I use for this?

8 Answers
cut -d ' ' -f 2

Where 2 is the field number of the space-delimited field you want.

You can also say:

cut -d\  -f 2

Note that there are two spaces after the backslash.

I have an answer (I admit somewhat confusing answer) that involvessed, regular expressions and capture groups:

  • \S* - first word
  • \s* - delimiter
  • (\S*) - second word - captured
  • .* - rest of the line

As a sed expression, the capture group needs to be escaped, i.e. \( and \).

The \1 returns a copy of the captured group, i.e. the second word.

$ echo "alpha beta gamma delta" | sed 's/\S*\s*\(\S*\).*/\1/'
beta

When you look at this answer, its somewhat confusing, and, you may think, why bother? Well, I'm hoping that some, may go "Aha!" and will use this pattern to solve some complex text extraction problems with a single sed expression.

Related