1

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

3 回答 3

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
于 2013-03-24T15:10:28.190 回答
2

只需将输出重定向到文件。

cat /pathway/to/your/file.txt % tr ' ' '\n' | sort | uniq -c | \
awk '{print $2"@"$1}' > myFile.txt
于 2013-03-24T13:22:33.387 回答
1

只需使用外壳重定向

 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 
于 2013-03-24T13:24:40.083 回答