
11111 1 11 1111111 1 1 1 1 1 1 1 111 1 1 1 1 11 11111111 1 11 1 11 11 1 11111 1 1
我有一個如圖所示的文件,但規模更大。我的目標是輸出111s、1s、11s、1111s等的數量。都在文件裡。我看到很多帖子都在談論做:
grep "\^word\" text_file
grep "\bword\b" text_file
grep -Fx "word" text_file
and so on...
所有這些要么什麼也不輸出,要么輸出整個文件。我該怎麼做才能只列出某些數字?
答案1
使用tr
,sort
和uniq
:
$ tr -s ' ' '\n' <file | sort | uniq -c
1
17 1
5 11
1 111
2 11111
1 1111111
1 11111111
這也為您提供了一個空白行的計數(上面輸出中的第一行),但您可以使用以下方法避免這種情況sed
:
$ tr -s ' ' '\n' <file | sed '/^$/d' | sort | uniq -c
17 1
5 11
1 111
2 11111
1 1111111
1 11111111
管道將所有空格更改為換行符,對結果行進行排序併計算每行出現的次數。
答案2
對於這個問題,我不會使用 grep,而是使用 awk:
$ a="11111 1 11 1111111 1 1 1 1 1 1 1 111 1 1 1 1 11 11111111 1 11 1 11 11 1 11111 1 1"
$ awk '{for (i=1;i<=NF;i++) ++seen[$i]}END{for (k in seen) print k,"found:"seen[k]}' <<<"$a"
1 found:17
11 found:5
111 found:1
11111 found:2
1111111 found:1
11111111 found:1
這個單行演示應該適用於您的整個文件(替換<<<"$a"
為yourfile
)