Strip leading and trailing spaces only in a shell variable with embedded spaces

I am trying to strip all leading and trailing spaces of a shell variable using either awk or sed or any other utility, however unscuccessful and need your help.

echo $SH_VAR | command_line Syntax.

The SH_VAR contains embedded spaces which needs to be preserved. I need only for the leading and trailing spaces to be removed. If anyone has accomplished this before or knows a quick way to achieve this result please let me know

Thnx :slight_smile:

#!/bin/ksh

a=' abc de f    '

b=$(echo ${a} | sed -e 's/^ *//g;s/ *$//g')

echo "a->[${a}] b->[${b}]"

delete leading whitespace (spaces, tabs)from begin of each line

sed 's/^[ \t]*//'

delete trailing whitespace (spaces, tabs)from end of each line

sed 's/[ \t]*$//'

try

sed 's/^[ \t]*//;s/[ \t]*$//' yourfilename

Thank you for the sed version.
the

echo $var1 | sed 's/^[ \t]//;s/[ \t]$//' |& read -p var2

strips the leading and trailing spaces from the variable var1 and sets the output to the new variable var2.

Thank you. :slight_smile:

I have encountered an issue in my previous command.

The command works for a variable with a single space embedded in it.
However when you have more than one space in the variable value the command strips extrac spaces and leaves only one inside of the value.

Ex: a=' abc de f '

returns b='abc de f'

however if a=' abc de f '
returns b='abc de f'

Any suggesstions to overcome this issue would be much appreciated. Thanks

We can extend vgersh99's code to handle this by adding a few double quotes...

#!/bin/ksh

a=' abc            de f    '

b=$(echo "${a}" | sed -e 's/^ *//g;s/ *$//g')

echo "a->[${a}] b->[${b}]"

The double quotes did the trick. Thanks for your input.
:slight_smile: