Bash Script to Capitalize First Letter of Each Word
Use
echo "$string" | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) substr($i,2)}1' to capitalize the first letter of each word in Bash.Examples
Inputhello world
OutputHello World
Inputbash scripting is fun
OutputBash Scripting Is Fun
Input123 easy as abc
Output123 Easy As Abc
How to Think About It
To capitalize the first letter of each word, split the input string into words, then for each word, change the first character to uppercase and keep the rest as is. Finally, join the words back together.
Algorithm
1
Get the input string.2
Split the string into words by spaces.3
For each word, convert the first letter to uppercase and keep the rest unchanged.4
Combine all words back into a single string.5
Output the transformed string.Code
bash
read -r input output=$(echo "$input" | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) substr($i,2)}1') echo "$output"
Output
Hello World
Dry Run
Let's trace the input 'hello world' through the code
1
Input read
input = 'hello world'
2
Process each word
Word 1: 'hello' -> 'H' + 'ello' = 'Hello' Word 2: 'world' -> 'W' + 'orld' = 'World'
3
Output combined
Output = 'Hello World'
| Word | Original | First Letter Uppercase | Result |
|---|---|---|---|
| 1 | hello | H | Hello |
| 2 | world | W | World |
Why This Works
Step 1: Splitting words
The awk command splits the input string into words using spaces.
Step 2: Capitalizing first letter
For each word, toupper(substr($i,1,1)) converts the first character to uppercase.
Step 3: Rebuilding words
The rest of the word is appended unchanged using substr($i,2), then all words are printed.
Alternative Approaches
Using Bash parameter expansion
bash
read -r input for word in $input; do printf '%s ' "${word^}" done echo
Simple and pure Bash, but splits on spaces only and may not handle punctuation well.
Using sed with regex
bash
read -r input echo "$input" | sed -E 's/(^| )[a-z]/\U&/g'
Uses sed to capitalize letters after spaces or start, but may be less readable.
Complexity: O(n) time, O(n) space
Time Complexity
The script processes each word once, so time grows linearly with input length.
Space Complexity
Extra space is used to store the output string, proportional to input size.
Which Approach is Fastest?
Bash parameter expansion is fastest for simple inputs; awk is more robust but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| awk command | O(n) | O(n) | Robust word capitalization |
| Bash parameter expansion | O(n) | O(n) | Simple scripts with space-separated words |
| sed regex | O(n) | O(n) | Quick inline substitutions with regex |
Use
awk for reliable word-by-word capitalization in Bash scripts.Trying to capitalize words without handling word boundaries, resulting in only the first letter of the whole string capitalized.