EN
Bash - trim string
3
points
In this article, we would like to show you how to trim string using Bash.
Quick solution:
echo ' text ' | awk 'match($0,/^\s*(.*)\s*$/,g){print g[1]}'
Note:
On the internet you can also find a solution using
xargs, however it was not created to trim text and may damage your code.
Practical example
In this example, we create a reusable function that uses awk to trim the string that we pass as the first argument ($1).
#!/bin/bash
function trim_string() {
echo "$1" | awk 'match($0,/^\s*(.*)\s*$/,g){print g[1]}'
}
# Usage example 1:
trim_string ' text '
Alternative solution
In this example, we present a script that uses Bash wildcards to trim whitespace characters from the variable string.
script.sh file:
#!/bin/bash
variable=" text "
# removes spaces from the beginning
variable="${variable#"${variable%%[![:space:]]*}"}"
# removes spaces from the end
variable="${variable%"${variable##*[![:space:]]}"}"
echo "$variable"
Run in command line:
./script.sh
Output:
text