jake reading
jake reading

Reputation: 79

Remove digits from end of string

I want to remove digits from end of a string.

Example:

 string123
 example545

Output:

string
example

Upvotes: 3

Views: 12707

Answers (5)

Benjamin W.
Benjamin W.

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

Claes Wikner
Claes Wikner

Reputation: 1517

awk '{sub(/[0-9]+$/,"")}1' file

string
example

Upvotes: 2

ctac_
ctac_

Reputation: 2471

With grep

echo S1tring123 | grep -o '.*[^0-9]'

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

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

Thomas Smyth
Thomas Smyth

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

Related Questions