我有兩個文本文件,文件1是這樣的:計算單詞的列表出現在文本文件中
apple
dog
cat
..
..
和File2看起來是這樣的:
appledogtree
dog
catapple
apple00001
..
..
我想算在出現從文件2文件1的單詞列表,並得到結果如下圖所示:
(字File1中,出現的次數在文件2)
apple 3
dog 2
cat 1
如何通過使用Bash命令行來執行此操作?
我有兩個文本文件,文件1是這樣的:計算單詞的列表出現在文本文件中
apple
dog
cat
..
..
和File2看起來是這樣的:
appledogtree
dog
catapple
apple00001
..
..
我想算在出現從文件2文件1的單詞列表,並得到結果如下圖所示:
(字File1中,出現的次數在文件2)
apple 3
dog 2
cat 1
如何通過使用Bash命令行來執行此操作?
考慮:
$ 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]}'
哪些呢:
cat f1.txt
提出到標準輸入文件的內容;xargs
將其翻譯爲一行;sed -e 's/ /\|/g'
將單詞加入"apple|dog|cat"
;grep -Eof /dev/stdin f2.txt
使用該模式打印模式的匹配;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
如果f1.txt很大,這可能會非常昂貴。 – codeforester
謝謝!這像一個魅力。 – user3260372
您可以使用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中的圖案。TXTsort | uniq -c
計數匹配模式awk
交換在uniq -c
輸出這就是我想要的,非常感謝你! – user3260372
很高興爲你效勞。 http://stackoverflow.com/help/someone-answers – codeforester
鑑於我的答案中有相同的輸入文件,'fgrep'沒有得到'cat' – dawg
在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
這不是一個規劃問題/ Q。但'grep'應該能夠幫助你。將來,請使用突出顯示的文本編輯框左上方的格式化工具將其格式化爲代碼/數據/輸出。祝你好運。 – shellter