Hug*_*lpz 1 linux shell awk frequency-analysis word-frequency
给定.txt文件,其中包含空格分隔的单词,例如:
But where is Esope the holly Bastard
But where is
Run Code Online (Sandbox Code Playgroud)
和Awk功能:
cat /pathway/to/your/file.txt | tr ' ' '\n' | sort | uniq -c | awk '{print $2"@"$1}'
Run Code Online (Sandbox Code Playgroud)
我在控制台中获得以下输出:
1 Bastard
1 Esope
1 holly
1 the
2 But
2 is
2 where
Run Code Online (Sandbox Code Playgroud)
如何打印到myFile.txt? 我实际上有300.000行和近200万字.最好将结果输出到文件中.
编辑:使用的答案(由@Sudo_O):
$ awk '{a[$1]++}END{for(k in a)print a[k],k}' RS=" |\n" myfile.txt | sort > myfileout.txt
Run Code Online (Sandbox Code Playgroud)
您的管道效率不高,您应该完成整个过程awk
:
awk '{a[$1]++}END{for(k in a)print a[k],k}' RS=" |\n" file > myfile
Run Code Online (Sandbox Code Playgroud)
如果您希望按排序顺序输出:
awk '{a[$1]++}END{for(k in a)print a[k],k}' RS=" |\n" file | sort > myfile
Run Code Online (Sandbox Code Playgroud)
管道给出的实际输出是:
$ tr ' ' '\n' < file | sort | uniq -c | awk '{print $2"@"$1}'
Bastard@1
But@2
Esope@1
holly@1
is@2
the@1
where@2
Run Code Online (Sandbox Code Playgroud)
注意:cat
在这里使用是无用的,我们可以直接重定向输入<
.这个awk
剧本也没有意义,它只是颠倒了单词和单词频率的顺序,并将它们分开@
.如果我们删除awk
脚本,输出更接近所需的输出(注意前面的间距但是它没有排序):
$ tr ' ' '\n' < file | sort | uniq -c
1 Bastard
2 But
1 Esope
1 holly
2 is
1 the
2 where
Run Code Online (Sandbox Code Playgroud)
我们可以sort
再次删除前导空格sed
:
$ tr ' ' '\n' < file | sort | uniq -c | sort | sed 's/^\s*//'
1 Bastard
1 Esope
1 holly
1 the
2 But
2 is
2 where
Run Code Online (Sandbox Code Playgroud)
但就像我在开始时提到的那样让我们awk
处理它:
$ awk '{a[$1]++}END{for(k in a)print a[k],k}' RS=" |\n" file | sort
1 Bastard
1 Esope
1 holly
1 the
2 But
2 is
2 where
Run Code Online (Sandbox Code Playgroud)