Bash脚本用于查找文件中每个字母的频率

Sky*_*eSM 21 linux bash frequency letters

我试图找出输入文件中英文字母中每个字母的出现频率.我怎样才能在bash脚本中执行此操作?

dog*_*ane 25

我的解决方案使用grep,sortuniq.

grep -o . file | sort | uniq -c
Run Code Online (Sandbox Code Playgroud)

忽略大小写:

grep -o . file | sort -f | uniq -ic
Run Code Online (Sandbox Code Playgroud)


gho*_*g74 15

只有一个awk命令

awk -vFS="" '{for(i=1;i<=NF;i++)w[$i]++}END{for(i in w) print i,w[i]}' file
Run Code Online (Sandbox Code Playgroud)

如果你想要不区分大小写,请添加 tolower()

awk -vFS="" '{for(i=1;i<=NF;i++)w[tolower($i)]++}END{for(i in w) print i,w[i]}' file
Run Code Online (Sandbox Code Playgroud)

如果你只想要人物,

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
Run Code Online (Sandbox Code Playgroud)

如果您只想要数字,请更改/[a-zA-Z]//[0-9]/

如果你不想显示unicode,那么 export LC_ALL=C


mou*_*iel 6

一个解决方案sed,sortuniq:

sed 's/\(.\)/\1\n/g' file | sort | uniq -c
Run Code Online (Sandbox Code Playgroud)

这会计算所有字符,而不仅仅是字母.您可以过滤掉:

sed 's/\(.\)/\1\n/g' file | grep '[A-Za-z]' | sort | uniq -c
Run Code Online (Sandbox Code Playgroud)

如果您想将大写和小写视为相同,只需添加翻译:

sed 's/\(.\)/\1\n/g' file | tr '[:upper:]' '[:lower:]' | grep '[a-z]' | sort | uniq -c
Run Code Online (Sandbox Code Playgroud)