EN
Bash - trim string
3 points
In this article, we would like to show you how to trim string using Bash.
Quick solution:
xxxxxxxxxx
1
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.
In this example, we create a reusable function that uses awk
to trim the string that we pass as the first argument ($1
).
xxxxxxxxxx
1
2
3
function trim_string() {
4
echo "$1" | awk 'match($0,/^\s*(.*)\s*$/,g){print g[1]}'
5
}
6
7
8
# Usage example 1:
9
10
trim_string ' text '
In this example, we present a script that uses Bash wildcards to trim whitespace characters from the variable
string.
script.sh
file:
xxxxxxxxxx
1
2
3
variable=" text "
4
5
# removes spaces from the beginning
6
variable="${variable#"${variable%%[![:space:]]*}"}"
7
8
# removes spaces from the end
9
variable="${variable%"${variable##*[![:space:]]}"}"
10
11
echo "$variable"
Run in command line:
xxxxxxxxxx
1
./script.sh
Output:
xxxxxxxxxx
1
text