给定一个用空格分隔的单词的 .txt 文件,例如:
But where is Esope the holly Bastard
But where is
Awk 函数:
cat /pathway/to/your/file.txt | tr ' ' '\n' | sort | uniq -c | awk '{print $2"@"$1}'
我在我的控制台中得到以下输出:
1 Bastard
1 Esope
1 holly
1 the
2 But
2 is
2 where
如何打印成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
最佳答案
您的管道效率不高,您应该在 awk
中完成所有工作相反:
awk '{a[$1]++}END{for(k in a)print a[k],k}' RS=" |\n" file > myfile
如果您希望按排序顺序输出:
awk '{a[$1]++}END{for(k in a)print a[k],k}' RS=" |\n" file | sort > myfile
您的管道给出的实际输出是:
$ tr ' ' '\n' < file | sort | uniq -c | awk '{print $2"@"$1}'
Bastard@1
But@2
Esope@1
holly@1
is@2
the@1
where@2
注意:使用 cat
在这里没用我们可以用 <
重定向输入. awk
脚本也没有意义,它只是颠倒单词和单词频率的顺序并用 @
分隔它们.如果我们删除 awk
脚本输出更接近所需的输出(但是请注意前面的间距并且它是未排序的):
$ tr ' ' '\n' < file | sort | uniq -c
1 Bastard
2 But
1 Esope
1 holly
2 is
1 the
2 where
我们可以 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
但就像我在开头提到的让 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
关于linux - awk: 一个文本文件中的词频,如何输出到myFile.txt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15598935/