• We did not send an email asking for donations - please read this post.

can you count letter or number frequency?

None-yet

Member
Joined
Aug 10, 2020
Messages
78
Reaction score
32
Credits
906
I know you can count word frequency using the command-line. But can you count letter or number frequency?
 


JasKinasis

Well-Known Member
Joined
Apr 25, 2017
Messages
1,562
Reaction score
2,224
Credits
11,517
This should probably do the trick:
Bash:
\grep -o . /path/to/file | sort | uniq -ic > /path/to/output-file
 

KGIII

Super Moderator
Staff member
Gold Supporter
Joined
Jul 23, 2020
Messages
7,334
Reaction score
6,325
Credits
59,450
I am a simple man...

Code:
fgrep -o $1 foo.txt | wc -l

Where $1 is your letter or number and 'foo.txt' is the file you want to check.

There are probably dozens of ways to do this. Don't make me pull out my rusty Perl skills!
 

KGIII

Super Moderator
Staff member
Gold Supporter
Joined
Jul 23, 2020
Messages
7,334
Reaction score
6,325
Credits
59,450
Hmm... There's also this:

Code:
awk '{c+=gsub(s,s)}END{print c}' s='a' test.txt

Sample output:
Code:
awk '{c+=gsub(s,s)}END{print c}' s='$1' foo.txt
196

Which matches the output from the first, so is presumably correct.

I ran both commands with 'time' and using awk is consistently the faster of the two. If you're working with a huge file, that'd probably shave off a few seconds.
 
OP
N

None-yet

Member
Joined
Aug 10, 2020
Messages
78
Reaction score
32
Credits
906
Thanks all. I have four dictionaries, I want to do my own char count to see for myself what chars are the most freq. Just read a book all about this topic that I found really interesting about words. Yea, my mom said I was weird. Used to read the newspapers/reference when I was 10.
 

KGIII

Super Moderator
Staff member
Gold Supporter
Joined
Jul 23, 2020
Messages
7,334
Reaction score
6,325
Credits
59,450
Oh, for that, you can do this:

Code:
sed 's/\(.\)/\1\n/g' $1 | sort | uniq -c

That'll include not just letters but numbers and other characters. That'll save you a ton of time and you won't have to run it multiple times for different characters.

Ain't the terminal awesome?!?
 

JasKinasis

Well-Known Member
Joined
Apr 25, 2017
Messages
1,562
Reaction score
2,224
Credits
11,517
Also, why do you have drum tab in your signature? What song is it for?
I was wondering that too!!!
The staves don’t line up properly in the tab in my browser either - so I had trouble reading it. Was going to copy paste it into a text editor later to get a better look!! Ha ha!!
 
$100 Digital Ocean Credit
Get a free VM to test out Linux!

Linux.org Hosting Donations
Consider making a donation

Members online


Top