Abu*_*e10 8 unix csv bash uniq
我有一个文本文件(list.txt),其中包含单个和多个单词的英语短语。我的目标是对每个单词进行字数统计并将结果写入 CSV 文件。
我已经弄清楚了写入每个单词的唯一实例数量的命令,按从最大到最小的顺序排序。该命令是:
$ tr 'A-Z' 'a-z' < list.txt | tr -sc 'A-Za-z' '\n' | sort | uniq -c | sort -n -r | less > output.txt
Run Code Online (Sandbox Code Playgroud)
问题在于新文件(output.txt)的格式化方式。前导有 3 个空格,后面是出现次数,后面是一个空格,最后是单词。然后转到下一行。例子:
9784 the
6368 and
4211 for
2929 to
Run Code Online (Sandbox Code Playgroud)
我需要做什么才能以更理想的格式(例如 CSV)获得结果?例如,我希望它是:
9784,the
6368,and
4211,for
2929,to
Run Code Online (Sandbox Code Playgroud)
更好的是:
the,9784
and,6368
for,4211
to,2929
Run Code Online (Sandbox Code Playgroud)
有没有办法使用 Unix 命令来执行此操作,或者我是否需要在文本编辑器或 Excel 中进行一些后处理?
使用awk方法如下:
> cat input
9784 the
6368 and
4211 for
2929 to
> cat input | awk '{ print $2 "," $1}'
the,9784
and,6368
for,4211
to,2929
Run Code Online (Sandbox Code Playgroud)
您的完整管道将是:
$ tr 'A-Z' 'a-z' < list.txt | tr -sc 'A-Za-z' '\n' | sort | uniq -c | sort -n -r | awk '{ print $2 "," $1}' > output.txt
Run Code Online (Sandbox Code Playgroud)