-->

AWK:从一个文本文件,如何输出中成MYFILE.TXT词频率是多少?(Awk: Words fre

2019-08-17 23:00发布

考虑到与空格分隔的单词, 如.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

Answer 1:

您的管道是不是很有效,你应该做这件事在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


Answer 2:

只是输出重定向到一个文件中。

cat /pathway/to/your/file.txt % tr ' ' '\n' | sort | uniq -c | \
awk '{print $2"@"$1}' > myFile.txt


Answer 3:

只需使用shell重定向 :

 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 


文章来源: Awk: Words frequency from one text file, how to ouput into myFile.txt?