Basics of String Trimming
Trimming Leading and Trailing Whitespace
One of the most basic string trimming operations in Bash is removing leading and trailing whitespace characters from a string. This can be achieved using the ${variable#pattern}
and ${variable%pattern}
parameter expansions.
## Example
variable=" Hello, World! "
trimmed_variable="${variable#"${variable%%[![:space:]]*}"}"
trimmed_variable="${trimmed_variable%"${trimmed_variable##*[![:space:]]}"}"
echo "$trimmed_variable" ## Output: "Hello, World!"
In the above example, we first remove the leading whitespace using the ${variable#"${variable%%[![:space:]]*}"}
expansion, which removes the longest prefix of the variable that matches the pattern "${variable%%[![:space:]]*}"
(the longest prefix of the variable that contains only whitespace characters).
Then, we remove the trailing whitespace using the ${trimmed_variable%"${trimmed_variable##*[![:space:]]}"}
expansion, which removes the longest suffix of the variable that matches the pattern "${trimmed_variable##*[![:space:]]}"
(the longest suffix of the variable that contains only whitespace characters).
Trimming Specific Characters
In addition to trimming whitespace, you can also trim specific characters from the beginning or end of a string using the same parameter expansion syntax.
## Example
variable="---Hello, World!+++"
trimmed_variable="${variable#"${variable%%[-+]*}"}"
trimmed_variable="${trimmed_variable%"${trimmed_variable##*[-+]}"}"
echo "$trimmed_variable" ## Output: "Hello, World!"
In this example, we're trimming the leading and trailing "-" and "+" characters from the string.
Handling Empty Strings
It's important to note that when working with string trimming, you should also consider the case of empty strings. Bash provides the :-
operator to handle this scenario.
## Example
variable=""
trimmed_variable="${variable#"${variable%%[![:space:]]*}"}"
trimmed_variable="${trimmed_variable%"${trimmed_variable##*[![:space:]]}"}"
echo "${trimmed_variable:-"The string is empty."}" ## Output: "The string is empty."
By using the :-
operator, we can provide a default value to be used if the trimmed variable is an empty string.