在linux bourne shell中:如何计算文件中特定单词的出现次数

时间:2012-05-15 00:38:27

标签: shell unix awk grep

通过 word ,我的意思是任何以空格分隔的字符串。

假设文件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次的命令吗?

7 个答案:

答案 0 :(得分:6)

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 }'

答案 1 :(得分:3)

grep -o '\<hello\>' filename | wc -l

\<\>位是字边界模式,因此表达式找不到foohellohellobar

您也可以使用awk -F '\\<hello\\>' ...来达到同样的效果。

答案 2 :(得分:2)

<强>解决方案:

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

答案 3 :(得分:0)

for word in `cat test.txt`; do
  if [[ ${word} == hello ]]; then
    helloCount=$(( ${helloCount} + 1));
  fi;
done;

echo ${helloCount} 

答案 4 :(得分:0)

a=$(printf "\01")
b=hello
sed -e "s/\<$b\>/ $a /g" -e "s/[^$a]//g" -e "s/$a/ $b /g" file | wc -w

答案 5 :(得分:0)

cat $FileName | tr '[\040]' '[\012]' | grep $word | wc -l

此命令将更改新行中的空格,然后您可以轻松地查找该单词并计算包含给定单词的行数。

答案 6 :(得分:0)

仅更改“针”和“文件”

#!/usr/bin/env sh

needle="|"
file="file_example.txt"

IFS=$'\n'

counter=0
for line in `cat $file`
do
    counter=$[$counter+1]
    echo $counter"|"`echo $line | grep -o "$needle" | wc -l`
done

它将打印行号和出现次数,用竖线字符

分隔