我有一个包含许多单词的字符串,每个单词之间至少有一个空格。我如何把字符串分割成单独的单词,这样我就可以循环遍历它们?
字符串作为参数传递。例如:${2}== "cat cat file"。我怎么循环呢?
另外,如何检查字符串是否包含空格?
我有一个包含许多单词的字符串,每个单词之间至少有一个空格。我如何把字符串分割成单独的单词,这样我就可以循环遍历它们?
字符串作为参数传递。例如:${2}== "cat cat file"。我怎么循环呢?
另外,如何检查字符串是否包含空格?
当前回答
对于我的用例,最好的选择是:
grep -oP '\w+' file
基本上,这是一个匹配连续非空格字符的正则表达式。这意味着任何类型和任何数量的空白都不匹配。-o参数在不同的行上输出每个匹配的单词。
其他回答
你试过把字符串变量传递给for循环吗?例如,Bash将自动对空白进行分割。
sentence="This is a sentence."
for word in $sentence
do
echo $word
done
This
is
a
sentence.
(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参数在不同的行上输出每个匹配的单词。
$ 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
echo $WORDS | xargs -n1 echo
这将输出每个单词,您可以处理该列表,因为您认为以后合适。