Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
What kind of shell? Bash, cmd.exe, powershell... ? – Alexey Sviridov Sep 24 '09 at 5:09
Do you just need to loop (e.g. execute a command for each of the words)? Or do you need to store a list of words for later use? – DVK Sep 24 '09 at 20:07

6 Answers

up vote 25 down vote accepted

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.
share|improve this answer
4  
The trick is to NOT quote the variable in the for command. – glenn jackman Sep 24 '09 at 10:24
@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 Sep 24 '09 at 20:04
1  
You could just append it to a variable: A=${A}${word}). – Lucas Jones Sep 24 '09 at 20:11

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]
share|improve this answer
3  
This is an excellent way to split the var so that individual parts may be accessed directly. +1; solved my problem – Cheekysoft Jul 26 '11 at 11:28
I was going to suggest using awk but set is much easier. I'm now a set fanboy. Thanks @Idelic! – Yzmir Ramirez Aug 18 '12 at 1:47

I like the conversion to an array, to be able to access individual elements:

    sentence="this is a story"
    stringarray=($sentence)

now you can access individual elements directly (it starts with 0):

    echo ${stringarray[0]}

or convert back to string in order to loop:

    for i in "${stringarray[@]}"
    do
      :
      # do whatever on $i
    done

Of course looping through the string directly was answered before, but that answer had the the disadvantage to not keep track of the individual elements for later use:

    for i in $sentence
    do
      :
      # do whatever on $i
    done

See also Bash Array Reference

share|improve this answer
Perfect solution, thanks for sharing – Thiago F Macedo Jun 30 at 11:35

For checking spaces just with bash:

[[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"
share|improve this answer

(A) To split a sentence into its words (space separated) you can simply use the default IFS by using

array=( $string )


Example running the following snippet

#!/bin/bash

sentence="this is the \"sentence\"   'you' want to split"
words=( $sentence )

len="${#words[@]}"
echo "words counted: $len"

printf "%s\n" "${words[@]}" ## print array

will output

words counted: 8
this
is
the
"sentence"
'you'
want
to
split

As you can see you can use single or double quotes too without any problem

Notes:
-- this is basically the same of mob's answer, but in this way you store the array for any further needing. If you only need a single loop, you can use his answer, which is one line shorter :)
-- please refer to this question for alternate methods to split a string based on delimiter.


(B) To check for a character in a string you can also use a regular expression match.
Example to check for the presence of a space character you can use:

regex='\s{1,}'
if [[ "$sentence" =~ $regex ]]
    then
        echo "Space here!";
fi
share|improve this answer
$ 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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.