我有一个包含许多单词的字符串,每个单词之间至少有一个空格。我如何把字符串分割成单独的单词,这样我就可以循环遍历它们?

字符串作为参数传递。例如:${2}== "cat cat file"。我怎么循环呢?

另外,如何检查字符串是否包含空格?


当前回答

(A)要将一个句子分成它的单词(空格分隔),你可以简单地使用默认的IFS

array=( $string )

运行以下代码片段的示例

#!/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

将输出

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

其他回答

你试过把字符串变量传递给for循环吗?例如,Bash将自动对空白进行分割。

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

 

This
is
a
sentence.
$ echo "This is   a sentence." | tr -s " " "\012"
This
is
a
sentence.

要检查空格,使用grep:

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

(A)要将一个句子分成它的单词(空格分隔),你可以简单地使用默认的IFS

array=( $string )

运行以下代码片段的示例

#!/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

将输出

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

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

foo
bar
baz

使用bash检查空格:

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