awk:一个文本文件中的词频,如何输出到myFile.txt?

2023-11-29

给定一个 .txt 文件用空格分隔的单词,例如:

But where is Esope the holly Bastard
But where is

And 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 ?我实际上有 30 万行,近 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这里没用,我们可以重定向输入<. The awkscript 也没有意义,它只是颠倒单词的顺序和单词的频率,并用一个分隔符@。如果我们放弃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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

awk:一个文本文件中的词频,如何输出到myFile.txt? 的相关文章

随机推荐