How to Use sed to Convert First Letter of Word to Uppercase


Often you may want to use sed to convert the first letter of each word in a file to uppercase.

You can use the following basic syntax to do so:

sed -e "s/\b\(.\)/\u\1/g" my_teams.txt

This particular example will convert the first letter of each word in the my_teams.txt file to uppercase.

Note that we use the s command to perform a substitution and we use the \b command to represent “word boundary” to convert the first character of each word to uppercase.

We also use the g command at the end to specify that this substitution should be made “globally”, i.e. the first letter of each word on each line in the file should be converted to uppercase.

The following example shows how to use this syntax in practice.

Example: How to Use sed to Convert First Letter of Each Word to Uppercase

Suppose we have a file named my_teams.txt that contains the names of various basketball teams:

Suppose that we would like to convert the first letter of each word in this file to uppercase.

We can use the following syntax to do so:

sed -e "s/\b\(.\)/\u\1/g" my_teams.txt

The following screenshot shows how to use this syntax in practice:

sed convert first letter of each word to uppercase

Notice that this converts the first letter of each word in the file to uppercase.

Note that we could also use the > command to save these results to a new file named my_teams_new.txt:

sed -e "s/\b\(.\)/\u\1/g" my_teams.txt > my_teams_new.txt

The following screenshot shows how to use this syntax in practice:

Notice that when we use the cat command to view the contents of my_teams_new.txt that it contains the same team names from the original file with the first letter of each word capitalized.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Replace All Text After Match
How to Use sed to Replace All Text Before Match
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply