Reputation: 79
I want to remove digits from end of a string.
Example:
string123
example545
Output:
string
example
Upvotes: 3
Views: 12707
Reputation: 52152
Without external tools, just parameter expansion and extended globbing:
$ shopt -s extglob
$ var=string123
$ echo "${var%%+([[:digit:]])}"
string
$ var=example545
$ echo "${var%%+([[:digit:]])}"
example
The +(pattern)
extended glob pattern is "one or more of this", so +([[:digit:]])
is "one or more digits".
The ${var%%pattern}
expansion means "remove the longest possible match of pattern
from the end of var
.
Upvotes: 13
Reputation: 89557
Not sure to fully understand your requirements, but try:
sed 's/[0-9]*\([^[:alnum:]]*\)$/\1/' file
or perhaps:
sed 's/[0-9]*\([^0-9]*\)$/\1/' file
Upvotes: 1
Reputation: 5644
Provided you have no other digits anywhere else in the string you can do:
echo string123 | sed 's/[0-9]//g'
string
And only the end of the string:
echo S1tring123 | sed 's/[0-9]\+$//'
S1tring
Where $
indicates the end of the line.
Upvotes: 6