shell脚本:按行搜索文件中的单词

时间:2014-05-06 03:07:07

标签: shell

我想从文件中搜索一个单词并显示该单词行的总出现次数。我知道解决这个问题的是grep命令:

echo "enter a word to search"
read word
echo "enter file name"
read file

grep $word $file

这就是我所知道的但我不知道如何打印该单词的总出现次数和直线出现次数。 我怎样才能做到这一点 ?这里是采样输出

file content
hello world in shell script 
hello world in hello script 
hello , hello world in hello script

预期产出

enter word to search = hello
total occurrence 6
line 1 occurrence 1
line 2 occurrence 2
line 3 occurrence 3

还有一件事,我知道计算单词。 wc -w $filename。但我不知道如何计算这个具体的词。

3 个答案:

答案 0 :(得分:2)

{{2p>原始答案:

$ awk '
BEGIN {
    printf "Enter a word to search: "
    getline word < "-"
}
{
line[NR] = gsub(word,"");
sum+=line[NR]
}
END {
print "total occurrence " sum;
for(i=1;i<=NR;i++)
    print "line " i " occurence " line[i]
}' inputfile

Enter a word to search: hello
total occurrence 7
line 1 occurence 1
line 2 occurence 2
line 3 occurence 3

答案 1 :(得分:0)

# Sample search term.
word='hello'

# Loop over all input lines; assumes input filename is `file`.
totalCount=0 counts=() # initialize variables
while IFS= read -r line; do
  # Count the occurrence of the search term on the current line.
  # `grep -o` outputs each occurrence on a separate line, so
  # by counting the output lines we know the occurrence count.
  count=$(grep -o "$word" <<<"$line" | wc -l)
      # Add to the output array of per-line occurrence counts.
  counts+=( $count )
      # Update the overall count.
  (( totalCount+= count ))
done < file

# Output
  # Total count.
echo "total occurence $totalCount"
  # Loop over the array with all per-line occurrence counts and 
  # output each.
for (( i = 1; i <= ${#counts[@]}; i++ )); do
  echo "line $i occurrences ${counts[i-1]}"
done

答案 2 :(得分:0)

请使用此选项

grep -n&#34;关键字&#34; &#34;文件名&#34;