How to trim whitespace from a Bash variable?

 

To trim whitespace from a Bash variable, you can use parameter expansion or a simple sed command. Here's how you can do it with examples:

Using Parameter Expansion:

bash
# Define a variable with leading and trailing whitespace my_var=" This is a Bash variable with whitespace. " # Trim leading and trailing whitespace trimmed_var="${my_var#"${my_var%%[![:space:]]*}"}" trimmed_var="${trimmed_var%"${trimmed_var##*[![:space:]]}"}" echo "Original variable: '$my_var'" echo "Trimmed variable: '$trimmed_var'"

In this example, we use parameter expansion to remove both leading and trailing whitespace from the my_var variable. The ${my_var%%[![:space:]]*} expression finds the longest substring of spaces at the beginning, and ${my_var##*[![:space:]]} finds the longest substring of spaces at the end.

Using sed Command:

bash
# Define a variable with leading and trailing whitespace my_var=" This is a Bash variable with whitespace. " # Trim leading and trailing whitespace using sed trimmed_var=$(echo "$my_var" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//') echo "Original variable: '$my_var'" echo "Trimmed variable: '$trimmed_var'"

In this example, we use the sed command to remove both leading and trailing whitespace. The -e option allows us to specify multiple commands, and s/^[[:space:]]*// removes leading spaces, while s/[[:space:]]*$// removes trailing spaces.

Both methods will trim leading and trailing whitespace from the Bash variable, resulting in the "Trimmed variable" containing the content without extra spaces.

Comments