I have some strings such as
ABC1
ABC2
TYFASDD12
They will only have letters and numbers. In each case I want to remove the last digit? The lengths will vary. So a hard coded substr won't work. What do I do?
if it doesn't end in a number, I don't want to remove any characters.
Yoda
March 13, 2014, 4:17pm
2
To remove last digit:
sed 's#[0-9]$##' file
To remove all trailing numbers:
sed 's#[0-9]*$##' file
str=TYFASDD12
# One trailing digit
echo "${str%[0-9]}"
# All trailing digits:
echo "${str%"${str##*[!0-9]}"}"
Boy is the shell SOOO flexible:-
OSX 10.7.5, default bash terminal, longhand...
(A little more complex than Scrutinzer's but another approach.)
Last login: Thu Mar 13 20:49:11 on ttys000
AMIGA:barrywalker~> strng="ABC1"
AMIGA:barrywalker~> echo "$strng"
ABC1
AMIGA:barrywalker~> strng="${strng:0:$(( ${#strng} - 1 ))}"
AMIGA:barrywalker~> echo "$strng"
ABC
AMIGA:barrywalker~> _
IMHO you can remove all trailing digits simply by using 2 percent signs instead of one...
$ str=ABCDEFGHI0123456789
$ echo ${str%%[0-9]*}
ABCDEFGHI
Hi shamrock.. no, that would not work:
$ str=ABC9DEFGHI0123456789
$ echo ${str%%[0-9]*}
ABC
Your string is different from the one i has but I see your point...