bash how to trim string

Answer

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 way how to remove whitespaces before and after word:

echo "   text.      text2 " | xargs

xargs remove all whitespaces before "text." and let one space bewteen text. and text2.

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

foo="hello"
echo "${foo::-1}"

Output: hell

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.