bash - 如何使用shell计算String中的单词数

标签 bash

我想使用 Shell 计算字符串中的单词数。

假设字符串是:

input="Count from this String"

这里的分隔符是空格 ' ' 预期输出是 4。 输入字符串中也可以有尾随空格字符,例如 "Count from this String "

如果字符串中有尾随空格,它应该产生相同的输出,即 4。我该怎么做?

最佳答案

echo "$input" | wc -w

使用wc -w 统计字数。

或者按照 dogbane 的建议, echo 也可以去掉:

wc -w <<< "$input"

如果 <<< 不被你的 shell 支持,你可以试试这个变体:

wc -w << END_OF_INPUT
$input
END_OF_INPUT

关于bash - 如何使用shell计算String中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15108229/

相关文章:

linux - 无法拉取 .vim/目录

linux - bash 脚本中的语法错误 : "(" unexpected -- with ! (*.sh)

python - 检查所有文件是否存在

python将视频转换为音频

linux - 使用 SED 进行网页抓取

bash - MD5进度输出-BASH

bash - Cygwin 中的 Rsync 命令失败

linux - 在 boot2docker 中使用 shell 命令

Bash 脚本 : save stream from Serial Port (/dev/ttyUSB0) to file until a specific input (e. g。 eof)出现

linux - 获取上个月修改的文件数