我的意思是任何空格分隔的字符串。
假设文件test.txt
有以下以空格分隔的单词:
hello hello hello hell osd
hello
hello
hello
hellojames beroo helloooohellool axnber hello
way
how
我想数一数单词hello出现在每一行的次数。
我使用命令awk -F "hello" '{print NF-1}' test.txt
来显示单词hello在每一行中出现的次数:
3
1
1
1
4
0
0
因此,它总共发现了3+1+1+1+4 = 10次。
问题是在第四行: hello只作为一个单独的单词出现1次;不应该计算hellojames和helloooohellool这样的单词,因为hello不是由空格分隔的。
因此,我希望它能找到7次出现的hello作为一个单独的词。
你能帮我写一个返回7次正确总数的命令吗?
发布于 2012-05-15 00:56:34
awk '{ for(i=1; i<=NF; i++) if($i=="hello") c++ } END{ print c }' file.txt
如果您需要它打印每一行:
awk '{ c=1; for(i=0; i<=NF; i++) if($i=="hello") c++; print c }'
发布于 2012-05-15 02:14:25
grep -o '\<hello\>' filename | wc -l
\<
和\>
位是字边界模式,所以表达式找不到foohello
或hellobar
。
您也可以使用awk -F '\\<hello\\>' ...
实现同样的效果。
发布于 2012-05-15 01:52:41
解决方案:
sed 's/\s\+/\n/g' test.txt | grep -w hello | wc -l
解释:
sed 's/\s\+/\n/g' text.txt
这将用换行符替换每一个空格,有效地重新格式化文件test.txt
,使其每行只有一个单词。sed 's/FIND/REPLACE/g'
命令将FIND
模式替换为随处可见的REPLACE
模式。模式\s\+
的意思是“一个或多个空白字符”,而\n
是一个换行符。
grep -w hello
这只提取那些包含hello
作为完整单词的行。
wc -l
这将计算行数。
如果要计算每行发生的次数,可以使用相同的技术,但一次只处理一行:
while read line; do
echo $line | sed 's/\s\+/\n/g' | grep -w hello | wc -l
done < test.txt
https://stackoverflow.com/questions/10592803
复制相似问题