Bash Script to Find Most Frequent Character
Use
echo "$input" | fold -w1 | sort | uniq -c | sort -nr | head -1 | awk '{print $2}' to find the most frequent character in a string in Bash.Examples
Inputhello
Outputl
Inputabracadabra
Outputa
Inputxyz
Outputx
How to Think About It
To find the most frequent character, split the string into single characters, count how many times each appears, then pick the one with the highest count.
Algorithm
1
Get the input string.2
Split the string into individual characters.3
Count how many times each character appears.4
Sort the counts in descending order.5
Return the character with the highest count.Code
bash
read -p "Enter a string: " input most_frequent_char=$(echo "$input" | fold -w1 | sort | uniq -c | sort -nr | head -1 | awk '{print $2}') echo "$most_frequent_char"
Output
l
Dry Run
Let's trace the input 'hello' through the code
1
Input string
input = 'hello'
2
Split into characters
h e l l o
3
Sort characters
e h l l o
4
Count unique characters
1 e 1 h 2 l 1 o
5
Sort counts descending
2 l 1 o 1 h 1 e
6
Select most frequent
l
| Count Character |
|---|
| 2 l |
| 1 o |
| 1 h |
| 1 e |
Why This Works
Step 1: Splitting characters
Using fold -w1 breaks the string into one character per line.
Step 2: Counting characters
The uniq -c command counts consecutive repeated lines, so sorting first groups same characters together.
Step 3: Finding the max
Sorting counts numerically in reverse order with sort -nr puts the most frequent character on top.
Alternative Approaches
Using awk only
bash
echo "$input" | awk '{for(i=1;i<=length;i++) c[substr($0,i,1)]++} END {for(k in c) if(c[k]>max){max=c[k];maxchar=k} print maxchar}'
This uses awk to count characters without external sort commands, but is less readable for beginners.
Using grep and tr
bash
echo "$input" | tr -cd '.[:alnum:]' | fold -w1 | sort | uniq -c | sort -nr | head -1 | awk '{print $2}'
This filters only alphanumeric characters before counting, useful if input has spaces or punctuation.
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting the characters dominates with O(n log n), where n is string length.
Space Complexity
Extra space is used to store characters and counts, O(n) in worst case.
Which Approach is Fastest?
The awk-only method avoids sorting and can be faster for large inputs but is less intuitive.
| Approach | Time | Space | Best For |
|---|---|---|---|
| fold + sort + uniq | O(n log n) | O(n) | Simple and readable scripts |
| awk only | O(n) | O(n) | Performance with large inputs |
| grep + tr + sort | O(n log n) | O(n) | Filtered inputs with punctuation |
Use
fold -w1 to split strings into characters in Bash.Forgetting to sort before using
uniq -c causes incorrect counts.