首页 > 解决方案 > 从字符串中grep一个字符/单词并计算Linux中出现的次数

问题描述

我喜欢从字符串中提取一个字符然后计算它,我没有从谷歌搜索中看到。请指教。我可能会错过搜索它。

node_count=`echo "test1|test2|test3" | grep "|" |wc -l`|echo $node_count

对我来说,输出总是 1。

1

请记住,我不是从文件中 grep,而是从一行字符串中 grep。文件中的 grep 很容易。

标签: linux

解决方案


您可能想使用以下选项-ogrep

$ node_count=`echo "test1|test2|test3" | grep  "|" -o |wc -l` && echo $node_count
# 2

推荐阅读