Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove digits from end of string

I want to remove digits from end of a string.

Example:

 string123
 example545

Output:

string
example
like image 523
jake reading Avatar asked Dec 19 '25 06:12

jake reading


2 Answers

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.

like image 114
Benjamin W. Avatar answered Dec 21 '25 01:12

Benjamin W.


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.

like image 36
Thomas Smyth - Treliant Avatar answered Dec 21 '25 02:12

Thomas Smyth - Treliant