Capitalizing a string

Bash:
Capitalizing a string

How to:

Bash does not have a built-in function specifically for capitalizing strings, but you can accomplish this task using parameter expansion or external tools like awk. Here are a few ways to capitalize a string in Bash:

Using Parameter Expansion:

This method manipulates the string directly in the shell.

str="hello world"
capitalized="${str^}"
echo "$capitalized"

Output:

Hello world

Using awk:

awk is a powerful text processing tool available on most Unix-like operating systems, which can be utilized to capitalize strings.

str="hello world"
echo "$str" | awk '{print toupper(substr($0, 1, 1)) tolower(substr($0, 2))}'

Output:

Hello world

Using sed:

For a more traditional approach, sed can be employed to capitalize the first letter of a string. However, it’s a bit more complex compared to the previous methods.

str="hello world"
echo "$str" | sed 's/./\u&/'

Output:

Hello world

These snippets demonstrate how to capitalize the first letter of a string in Bash, highlighting the flexibility of shell scripting when manipulating text.