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

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

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


当前回答

echo $WORDS | xargs -n1 echo

这将输出每个单词,您可以处理该列表,因为您认为以后合适。

其他回答

我喜欢转换为数组,以便能够访问单个元素:

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

现在你可以直接访问单个元素(它以0开头):

echo ${stringarray[0]}

或者转换回字符串以进行循环:

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

当然,之前已经回答了直接遍历字符串的问题,但这个回答的缺点是不能跟踪单独的元素以供以后使用:

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

参见Bash数组参考。

(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

对于我的用例,最好的选择是:

grep -oP '\w+' file

基本上,这是一个匹配连续非空格字符的正则表达式。这意味着任何类型和任何数量的空白都不匹配。-o参数在不同的行上输出每个匹配的单词。

只需使用shell内置的“set”即可。例如,

set $text

在此之后,$text中的单个单词将以$1、$2、$3等形式存在。对于健壮性,通常是这样做的

set -- junk $text
shift

处理$text为空或以破折号开头的情况。例如:

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

这个打印

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

使用bash检查空格:

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