Shell

How to trim space from bash variable

bashA small tip for removing spaces from Bash shell variables. To remove trailing spaces, use:

sed 's/ *$//g'

Example:

echo " www ezylinux com " | sed 's/ *$//g'

Output:

<SPACE>www ezylinux com

To remove leading spaces, use:

sed 's/^ *//g'

Example:

echo " www ezylinux com " | sed 's/^ *//g'

Output:

www ezylinux com<SPACE>

To remove both leading and trailing spaces, use:

sed -e 's/^ *//g' -e 's/ *$//g'

Example:

echo " www ezylinux com " | sed -e 's/^ *//g' -e 's/ *$//g'

Output:

www ezylinux com
EOF.← Back to articles