Bash How to Trim String

Bash How to Trim String

You can use a bash parameter expansion, sed, cut, and tr to trim a string.

Let’s use bash parameter expansion to remove all whitespace characters from the variable foo:

foo="Hello world."
echo "${foo//[["space:]]/}"

Output: Helloworld.

“${foo// /}” removes all space characters, “$foo/ /” removes the first space character.

To remove only space characters before and after string use sed:

foo=" Hello world. "
echo "${foo}" | sed -e 's/^[[:space:]]*//'

Output: Hello world.

Easy to use and remember the way how to remove whitespaces before and afterword:

echo " text. text2 " | xargs

xargs remove all whitespaces before “text.” and let one space between text. and text2.

If you want to delete only the last character from the variable:

echo "${foo::-1}"

Output: hell

Leave a Comment