Bash Script to Sort Characters in a String
Use
echo "$string" | grep -o . | sort | tr -d '\n' in Bash to sort characters in a string alphabetically.Examples
Inputstring
Outputginrst
Inputbashscript
Outputabchiprsst
Inputa
Outputa
How to Think About It
To sort characters in a string, first split the string into individual characters, then sort these characters alphabetically, and finally join them back into a single string.
Algorithm
1
Get the input string.2
Split the string into single characters, one per line.3
Sort the characters alphabetically.4
Join the sorted characters back into one string.5
Print the sorted string.Code
bash
#!/bin/bash string="bashscript" sorted=$(echo "$string" | grep -o . | sort | tr -d '\n') echo "$sorted"
Output
abchiprsst
Dry Run
Let's trace the string 'bash' through the code
1
Input string
string = 'bash'
2
Split characters
b\na\ns\nh
3
Sort characters
a\nb\ns\nh
4
Join characters
absh
| Step | Characters |
|---|---|
| Split | b,a,s,h |
| Sort | a,b,s,h |
| Join | absh |
Why This Works
Step 1: Split string into characters
Using grep -o . breaks the string into one character per line.
Step 2: Sort characters
The sort command arranges these characters alphabetically.
Step 3: Join characters back
The tr -d '\n' removes newlines to join characters into a single sorted string.
Alternative Approaches
Using Bash array and sort command
bash
#!/bin/bash string="bashscript" arr=($(echo "$string" | fold -w1 | sort)) sorted="${arr[*]}" sorted=${sorted// /} echo "$sorted"
This uses an array to hold characters, then joins them after sorting; slightly more complex but clear.
Using pure Bash with parameter expansion and sort
bash
#!/bin/bash string="bashscript" sorted=$(printf "%s\n" $(echo "$string" | grep -o .) | sort | tr -d '\n') echo "$sorted"
Similar to main method but uses printf for splitting; slightly different syntax.
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting characters takes O(n log n) time where n is the string length, due to the sorting step.
Space Complexity
Extra space is needed to hold the split characters and the sorted result, so O(n) space.
Which Approach is Fastest?
All approaches rely on sorting, so time complexity is similar; using arrays may add slight overhead but improves readability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| grep + sort + tr | O(n log n) | O(n) | Simple and concise scripts |
| Bash array + sort | O(n log n) | O(n) | Clearer code with arrays |
| printf + grep + sort | O(n log n) | O(n) | Alternative syntax preference |
Use
grep -o . to split a string into characters in Bash.Forgetting to remove newlines after sorting, which results in multi-line output instead of a single string.