我有如下文件:
这是一个示例文件
该文件将用于测试
this is a sample file
this file will be used for testing
我想用AWK来统计单词数。
预期输出是
this 2
is 1
a 1
sample 1
file 2
will 1
be 1
used 1
for 1
我写了下面的 AWK,但出现了一些错误
cat anyfile.txt|awk -F" "'{for(i=1;i<=NF;i++) a[$i]++} END {for(k in a) print k,a[k]}'
这对我来说可以:
awk '{for(i=1;i<=NF;i++) a[$i]++} END {for(k in a) print k,a[k]}' testfile
used 1
this 2
be 1
a 1
for 1
testing 1
file 2
will 1
sample 1
is 1
PS不需要设置-F" "
,因为它默认为空白。
PS2,请勿使用cat
使用可以读取数据本身的程序,例如awk
你可以加sort
后面的代码对其进行排序。
awk '{for(i=1;i<=NF;i++) a[$i]++} END {for(k in a) print k,a[k]}' testfile | sort -k 2 -n
a 1
be 1
for 1
is 1
sample 1
testing 1
used 1
will 1
file 2
this 2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)