2017-01-30 91 views
3

我有兩個文本文件,文件1是這樣的:計算單詞的列表出現在文本文件中

apple 
dog 
cat 
.. 
.. 

和File2看起來是這樣的:

appledogtree 
dog 
catapple 
apple00001 
.. 
.. 

我想算在出現從文件2文件1的單詞列表,並得到結果如下圖所示:

(字File1中,出現的次數在文件2)

apple 3 
dog 2 
cat 1 

如何通過使用Bash命令行來執行此操作?

+0

這不是一個規劃問題/ Q。但'grep'應該能夠幫助你。將來,請使用突出顯示的文本編輯框左上方的格式化工具將其格式化爲代碼/數據/輸出。祝你好運。 – shellter

回答

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提出到標準輸入文件的內容;
  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]}'統計單詞並打印計數。

隨着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 
+0

如果f1.txt很大,這可能會非常昂貴。 – codeforester

+1

謝謝!這像一個魅力。 – user3260372

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提取所有匹配的零件(-o選項)f2.txt基於f1中的圖案。TXT
  • sort | uniq -c計數匹配模式
  • 最後,awk交換在uniq -c輸出
+1

這就是我想要的,非常感謝你! – user3260372

+0

很高興爲你效勞。 http://stackoverflow.com/help/someone-answers – codeforester

+0

鑑於我的答案中有相同的輸入文件,'fgrep'沒有得到'cat' – dawg

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 
相關問題