Operating System - HP-UX
1833828 Members
2407 Online
110063 Solutions
New Discussion

Removing the last Character from a variable

 
SOLVED
Go to solution
Tommy_6
Regular Advisor

Removing the last Character from a variable

Just a quick questions for you Guru's. I need to remove the last character from a variable in a C Shell script. For example:

VAR = foobar

needs to be

VAR = fooba

I need the "r" removed from foobar. The variable is never the same lenght. Thanks in advance.

Tommy
6 REPLIES 6
Sridhar Bhaskarla
Honored Contributor

Re: Removing the last Character from a variable

Hi Tommy,

One way is

VAR=$(echo $VAR |cut -c 1-$(echo "$(echo $VAR|wc -c)-2"|bs))

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
Michael Schulte zur Sur
Honored Contributor

Re: Removing the last Character from a variable

Hi,

another way is:
VAR=`echo foobar | awk '{print substr($0,1,length($0)-1)}'`
VAR=`echo foobar|sed 's/.$//'`
VAR=`expr "foobar" : "\(.*\).$"`

greetings,

Michael

Laurie Gellatly
Honored Contributor

Re: Removing the last Character from a variable

try:
var=`echo $x | sed -e 's/.$//'`
there may be a better/easier way but
heck, it works!


...Laurie :{)
If you're not using OverTime, you're doing overtime!
Laurie Gellatly
Honored Contributor

Re: Removing the last Character from a variable

try:
var=`echo $var | sed -e 's/.$//'`
there may be a better/easier way but
heck, it works!


...Laurie :{)
If you're not using OverTime, you're doing overtime!
curt larson_1
Honored Contributor
Solution

Re: Removing the last Character from a variable

var="foobar"
var=${var%?}
print $var
Dietmar Konermann
Honored Contributor

Re: Removing the last Character from a variable

Tommy,

Curt's approach is BY FAR the best solution in this thread and deserves the 10pts. All other approaches use subshells, pipes, external commands and thus cause thremendous fork/exec activity during execution.

We see often terrible performance problems on machines that are caused by terribly bad coded shell scripts. PLEASE try to use shell built-ins whenever this is possible.

OK, when the script is supposed to run rarely... no problem. :-)

Just my 2 cents...
Dietmar.
"Logic is the beginning of wisdom; not the end." -- Spock (Star Trek VI: The Undiscovered Country)