3

I want to remove digits from end of a string.

Example:

 string123
 example545

Output:

string
example
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
jake reading
  • 79
  • 1
  • 1
  • 5

5 Answers5

13

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
6

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.

Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36
  • what if string contains say " S1tring123 " I wish to only remove the ending digits, so remove digits up until alpha type of thing – jake reading Jan 06 '18 at 19:55
  • 2
    Well it is important in the first one as that would remove only the first digit :) – PesaThe Jan 06 '18 at 20:04
2

With grep

echo S1tring123 | grep -o '.*[^0-9]'
ctac_
  • 2,413
  • 2
  • 7
  • 17
2
awk '{sub(/[0-9]+$/,"")}1' file

string
example
Claes Wikner
  • 1,457
  • 1
  • 9
  • 8
1

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
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125