views:

3476

answers:

4

I have a string, like a sentence, and I know for sure that there are many words with at least one space separate every adjacent two. How can I split the words into individual strings so I can loop through them?


EDIT: Bash The string is passed in as an argument. e.g. ${2} might be "cat '' cat '' file". so how can I loop through this arg ${2}?


Also, how to check if a string contains spaces?

+5  A: 

Did you try just passing the string variable to a for loop? Bash, for one, will split on whitespace automatically.

sentence="This is   a sentence."
for word in $sentence
do
    echo $word
done

 

This
is
a
sentence.
mobrule
The trick is to NOT quote the variable in the for command.
glenn jackman
@MobRule - the only drawback of this is that you can not easily capture (at least I don't recall of a way) the output for further processing. See my "tr" solution below for something that sends stuff to STDOUT
DVK
You could just append it to a variable: `A=${A}${word})`.
Lucas Jones
+1  A: 
$ echo "This is   a sentence." | tr -s " " "\012"
This
is
a
sentence.

For checking for spaces, use grep:

$ echo "This is   a sentence." | grep " " > /dev/null
$ echo $?
0
$ echo "Thisisasentence." | grep " " > /dev/null     
$ echo $?
1
DVK
A: 

For checking spaces just with bash:

[[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"
glenn jackman
A: 

Just use the shells "set" built-in. For example,

set $text

After that, individual words in $text will be in $1, $2, $3, etc. For robustness, one usually does

set -- junk $text
shift

to handle the case where $text is empty or start with a dash. For example:

text="This is          a              test"
set -- junk $text
shift
for word; do
  echo "[$word]"
done

This prints

[This]
[is]
[a]
[test]
Idelic