给定.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
答案 0 :(得分:5)
您的管道效率不高,您应该在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
答案 1 :(得分:2)
只需将输出重定向到文件即可。
cat /pathway/to/your/file.txt % tr ' ' '\n' | sort | uniq -c | \
awk '{print $2"@"$1}' > myFile.txt
答案 2 :(得分:1)
只需使用shell redirection:
echo "test" > overwrite-file.txt
echo "test" >> append-to-file.txt
一个有用的命令是tee
,允许重定向到文件并仍然看到输出:
echo "test" | tee overwrite-file.txt
echo "test" | tee -a append-file.txt
我发现你正在使用亚洲脚本,你需要小心你的系统使用的语言环境,因为结果排序可能不是你所期望的那样:
*警告* 环境指定的区域设置会影响排序顺序。设置LC_ALL = C以获取使用本机字节值的传统排序顺序。
看一下输出:
locale