[英]Bash script to find the frequency of every letter in a file
我试图找出输入文件中英文字母中每个字母的出现频率。 我怎样才能在bash脚本中执行此操作?
我的解决方案使用grep
, sort
和uniq
。
grep -o . file | sort | uniq -c
忽略大小写:
grep -o . file | sort -f | uniq -ic
只有一个awk命令
awk -vFS="" '{for(i=1;i<=NF;i++)w[$i]++}END{for(i in w) print i,w[i]}' file
如果你想要不区分大小写,请添加tolower()
awk -vFS="" '{for(i=1;i<=NF;i++)w[tolower($i)]++}END{for(i in w) print i,w[i]}' file
如果你只想要角色,
awk -vFS="" '{for(i=1;i<=NF;i++){ if($i~/[a-zA-Z]/) { w[tolower($i)]++} } }END{for(i in w) print i,w[i]}' file
如果您只想要数字,请更改/[a-zA-Z]/
至/[0-9]/
如果您不想显示unicode,请export LC_ALL=C
sed
, sort
和uniq
解决方案:
sed 's/\(.\)/\1\n/g' file | sort | uniq -c
这会计算所有字符,而不仅仅是字母。 您可以过滤掉:
sed 's/\(.\)/\1\n/g' file | grep '[A-Za-z]' | sort | uniq -c
如果您想将大写和小写视为相同,只需添加翻译:
sed 's/\(.\)/\1\n/g' file | tr '[:upper:]' '[:lower:]' | grep '[a-z]' | sort | uniq -c
这是一个建议:
while read -n 1 c
do
echo "$c"
done < "$INPUT_FILE" | grep '[[:alpha:]]' | sort | uniq -c | sort -nr
类似于上面的mouviciel的答案,但对于BSD系统上使用的Bourne和Korn shell更通用,当你没有GNU sed,它支持替换中的\\ n时,你可以反斜杠转义换行符:
sed -e's/./&\
/g' file | sort | uniq -c | sort -nr
或者为了避免屏幕上的可视分割,请按CTRL + V CTRL + J类型插入文字换行符
sed -e's/./&\^J/g' file | sort | uniq -c | sort -nr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.