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

标签 linux shell awk frequency-analysis word-frequency

给定一个用空格分隔的单词的 .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/

相关文章:

linux - 如何在 Ionic/Capacitor 中设置 Android Studio 的正确路径?

linux - Bash 脚本没有扩展我的 $file 变量?

shell脚本没有执行

awk - 根据特定列的修改拆分表文件

linux - 如果需要,在文本文件 linux 的每一行中添加特定模式

c - 获取 X11 窗口标题高度

linux - 为什么我会收到 malloc 错误?

c# - 如何在Linux服务器上轻松运行C#代码?

git - 无法从 crontab 作业中提交 git

awk - 如何用awk填充以下字段的空格?