如何从字符串使用shell算字数 [英] How to count number of words from String using shell
问题描述
我想从使用壳牌的String计算单词数量。
假设字符串是:
输入=从这个字符串计数
下面的分隔符是空间和预期输出为4。
此外,还可以在像输入字符串从这个字符串计数
。尾部的空格字符
如果有在字符串尾随空格,它应该产生相同的输出,即4.我如何能做到这一点?
回声$输入| WC -w
使用WC -w来计算单词的数量。
或按罗布麻的建议下,回声可以摆脱的还有:
WC -w<<< $输入
如果<<<不是由你的shell支持你可以试试这个变种:
WC -w<< END_OF_INPUT
$输入
END_OF_INPUT
I want to count number of words from a String using Shell.
Suppose the String is:
"input=Count from this String"
Here the delimiter is space ' '
and expected output is 4.
There can also be trailing space characters in the input string like "Count from this String "
.
If there are trailing space in the String, it should produce the same output, that is 4. How can I do this?
echo "$input" | wc -w
Use wc -w to count the number of words.
Or as per dogbane's suggestion, the echo can be got rid of as well:
wc -w <<< "$input"
If <<< is not supported by your shell you can try this variant:
wc -w << END_OF_INPUT
$input
END_OF_INPUT
这篇关于如何从字符串使用shell算字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!