1834882 Members
2137 Online
110071 Solutions
New Discussion

Re: script

 
SOLVED
Go to solution
Ana Perez_3
Occasional Contributor

script

Hello:

How can I eliminate the last character of a string in a shell script?

for example

pepitoA

to

pepito

Regards,
Mario.
10 REPLIES 10
Sanjay Kumar Suri
Honored Contributor

Re: script

Use vi

:s/oldtext/newtext/g

sks
A rigid mind is very sure, but often wrong. A flexible mind is generally unsure, but often right.
Nicolas Dumeige
Esteemed Contributor
Solution

Re: script

Hello Mario,

One way to do it :

#!/bin/ksh
var="012345"
length=${#var}
(( length -= 1 ))
echo $var | cut -c1-$length

cheers
All different, all Unix
Mark Grant
Honored Contributor

Re: script

Or simply

expr "pepitoA" : "\(.*\)."
Never preceed any demonstration with anything more predictive than "watch this"
Francisco J. Soler
Honored Contributor

Re: script

Hi Mario,

try this script:

STRING_A=pepitoA

STRING_B=`echo $STRING_A | awk '{printf("%s",substr($0,1,length($0)-1))}'`

echo $STRING_B

Be careful with the quotation.

Frank.
Linux?. Yes, of course.
Hoefnix
Honored Contributor

Re: script

Hi,
or use AWK.

echo pepitoA | awk '{ n=length($0)-1; print substr( $0, 0, n) }'

HTH,
Peter
Nicolas Dumeige
Esteemed Contributor

Re: script

... or
# echo PepitoA | sed -e 's/.$//'
:)
All different, all Unix
Steve Steel
Honored Contributor

Re: script

Hi

From shell man

${parameter%pattern}
${parameter%%pattern}
If the shell pattern matches the end of the
value of parameter, the value of parameter
with the matched part is deleted; otherwise
substitute the value of parameter. In the
former, the smallest matching pattern is
deleted; in the latter, the largest matching
pattern is deleted.


/home/steves >p=pepitoA
/home/steves >p=${p%?}
/home/steves >echo $p
pepito

Steve Steel


If you want truly to understand something, try to change it. (Kurt Lewin)
Francisco J. Soler
Honored Contributor

Re: script

Hi Steve,

I think your answer is the best one. I take note of it.
Congratulations.

Frank.
Linux?. Yes, of course.
Shyjith P K
Frequent Advisor

Re: script

Hi

You can use

sed 's/oldtext/netext/g' filename >filename

cheers
Shyjith
Kiyoshi Miyake
Frequent Advisor

Re: script

Hi.

The solusion of Steve is wonderful!

My solution :
printf "pepitoA" | perl -pe chop

(perl4 ok)