Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to find the frequency of every letter in a file

I am trying to find out the frequency of appearance of every letter in the english alphabet in an input file. How can I do this in a bash script?

like image 649
SkypeMeSM Avatar asked Oct 19 '10 09:10

SkypeMeSM


People also ask

How do I count the number of letters in a string in bash?

you can use wc to count the number of characters in the file wc -m filename. txt.

What is $@ in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do you use tr in bash?

`tr` command can be used with -c option to replace those characters with the second character that don't match with the first character value. In the following example, the `tr` command is used to search those characters in the string 'bash' that don't match with the character 'b' and replace them with 'a'.

How do you count the number of words in a shell?

Using wc command. wc command is used to know the number of lines, word count, byte and characters count etc. Count the number of words using wc -w.


2 Answers

My solution using grep, sort and uniq.

grep -o . file | sort | uniq -c 

Ignore case:

grep -o . file | sort -f | uniq -ic 
like image 154
dogbane Avatar answered Sep 28 '22 15:09

dogbane


Just one awk command

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

if you want case insensitive, add tolower()

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

and if you want only characters,

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 

and if you want only digits, change /[a-zA-Z]/ to /[0-9]/

if you do not want to show unicode, do export LC_ALL=C

like image 34
ghostdog74 Avatar answered Sep 28 '22 17:09

ghostdog74