How to split one string into multiple strings separated by at least one space in bash shell?

Viewed 520724

I have a string containing many words with at least one space between each two. How can I split the string into individual words so I can loop through them?

The string is passed as an argument. E.g. ${2} == "cat cat file". How can I loop through it?

Also, how can I check if a string contains spaces?

11 Answers
echo $WORDS | xargs -n1 echo

This outputs every word, you can process that list as you see fit afterwards.

$ echo foo bar baz | sed 's/ /\n/g'

foo
bar
baz

For my use case, the best option was:

grep -oP '\w+' file

Basically this is a regular expression that matches contiguous non-whitespace characters. This means that any type and any amount of whitespace won't match. The -o parameter outputs each word matches on a different line.

Another take on this (using Perl):

$ echo foo bar baz | perl -nE 'say for split /\s/'
foo
bar
baz
Related