计算文本文件中单词列表的出现次数

时间:2017-01-30 04:13:17

标签: bash

我有两个文本文件,File1看起来像这样:

apple
dog
cat
..
..

和File2看起来像这样:

appledogtree 
dog
catapple
apple00001
..
..

我想计算File2中File1的单词列表的出现次数,并得到如下结果:

(File1中的单词,File2中出现的次数)

apple 3
dog 2
cat 1

如何使用Bash命令行执行此操作?

3 个答案:

答案 0 :(得分:2)

假设:

$ cat f1.txt
apple
dog
cat
$ cat f2.txt
appledogtree 
dog
catapple
apple00001

尝试:

while IFS= read -r line || [[ -n $line ]]; do 
    printf "%s->%s\n" $line "$(grep -c $line f2.txt)"
done <f1.txt

打印:

apple->3
dog->2
cat->1

如果你想要一个管道,你可以这样做:

cat f1.txt | xargs | sed -e 's/ /\|/g' | grep -Eof /dev/stdin f2.txt | awk '{a[$1]++} END{for (x in a) print x, a[x]}'

其中:

  1. cat f1.txt将文件的内容放入stdin;
  2. xargs将其转换为一行;
  3. sed -e 's/ /\|/g'将这些字词加入"apple|dog|cat";
  4. grep -Eof /dev/stdin f2.txt使用该模式打印模式的匹配项;
  5. awk '{a[$1]++} END{for (x in a) print x, a[x]}'计算单词并打印计数。
  6. 使用GNU grep,您可以执行grep -Eof - f2.txt

    该管道适用于POSIX和Linux ......

    如果你想要纯效率,只需使用awk:

    awk 'NR==FNR {pat[FNR]=$1; next} 
                 {for (i in pat){ if(match($0, pat[i])){m[pat[i]]++}}} 
                 END{for(e in m){print e,m[e]}}'  f1.txt f2.txt
    

答案 1 :(得分:2)

您可以使用fgrep来有效地执行此操作:

fgrep -of f1.txt f2.txt | sort | uniq -c | awk '{print $2 " " $1}'

给出这个输出:

apple 3
cat 1
dog 2
  • fgrep -of f1.txt f2.txt根据f1.txt中的模式提取f2.txt的所有匹配部分(-o选项)
  • sort | uniq -c计算匹配模式
  • 最后,awk交换了uniq -c输出
  • 中单词的顺序

答案 2 :(得分:1)

在awk中:

$ awk 'NR==FNR { a[$1]; next }                  # read in all search words
               { for(i in a) a[i]+=gsub(i,i) }  # count matches of all keywords in record
            END{ for(i in a) print i,a[i] }     # output results
' file1 file2
apple 3
cat 1
dog 2
相关问题