1825766 Members
2054 Online
109687 Solutions
New Discussion

Re: Trim a variable

 
intp
Frequent Advisor

Trim a variable

How to trim a variable in UNIX (shell script) ? any built-in function avbl ?
9 REPLIES 9
Rodney Hills
Honored Contributor

Re: Trim a variable

If you want to delete trailing blanks for instance-

x="ab "
y=${x%% *}

HTH

-- Rod Hills
There be dragons...
Jeff_Traigle
Honored Contributor

Re: Trim a variable

What do you mean by "trim a variable"? An example of what you're trying to accomplish would be useful, I think.
--
Jeff Traigle
Torsten.
Acclaimed Contributor

Re: Trim a variable

Trim a variable?

To set a variable to "empty", use this:

# export myvar=1
# echo $myvar
1

# export myvar=
# echo $myvar

#

the "export myvar=" sets myvar to an empty value.
# unset myvar

is deleting the variable.

Hope this helps!
Regards
Torsten.

__________________________________________________
There are only 10 types of people in the world -
those who understand binary, and those who don't.

__________________________________________________
No support by private messages. Please ask the forum!

If you feel this was helpful please click the KUDOS! thumb below!   
intp
Frequent Advisor

Re: Trim a variable

trim .. i want to remove leading and trailing blanks

e.g
a=" Hello "

output
"Hello" [ no space before and after]

Rodney Hills
Honored Contributor

Re: Trim a variable

To remove preceding blanks-

y=${a# *}

HTH

-- Rod Hills
There be dragons...
Rodney Hills
Honored Contributor

Re: Trim a variable

Dis-regard my previous post, here is a method to trim blanks-

typeset -L b=$a
c=${b%% *}
echo "c is =$c="

HTH

-- Rod Hills
There be dragons...
A. Clay Stephenson
Acclaimed Contributor

Re: Trim a variable

Here's a sneaky way leveraging read.

X=" hello "
echo "Before: \"${X}\""
echo "${X}" | read X
echo "After : \"${X}\""

If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: Trim a variable

Hi:

Analogous to Clay's solution for trimming leading and trailing blanks:

#/usr/bin/sh
a=" hello "
echo "Before: [${a}]"
a=`echo ${a}`
echo "After : [${a}]"

Note that the variable is re-assigned to itself as the lvalue of 'echo'ing it.

Regards!

...JRF...
Arturo Galbiati
Esteemed Contributor

Re: Trim a variable

Hi,
a=" hello "
a=$(echo "$a"|tr -d " ")

This removes all spaces in the var non only leading and trailing.

To remove leading and trailing:
a=" h ello "
a=$(echo "$a"|sed 's/^ *//g;s/ *$//g')


HTH,
Art