vins
vins

Reputation: 55

unix shell sub string?

I want to extract substring till the point the last numeric ends.

for example:

In the string "abcd123z" , I want the output to be "abcd123"

In the string "abcdef123gh01yz" , I want the output to be "abcdef123gh01"

In the string "abcd123" , I want the output to be "abcd123"

How to do this in the unix shell?

Upvotes: 2

Views: 269

Answers (3)

Deleted User
Deleted User

Reputation: 2541

tmp="${str##*[0-9]}"     # cut off all up to last digit, keep intermediate
echo "${str%$tmp}"        #  remove intermediate from end of string

Upvotes: 1

anubhava
anubhava

Reputation: 785196

You can do this in BASH regex:

str='abcdef123gh01yz'
[[ "$str" =~ ^(.*[[:digit:]]) ]] && echo "${BASH_REMATCH[1]}"
abcdef123gh01

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Try this sed command,

sed 's/^\(.*[0-9]\).*$/\1/g' file

Example:

$ echo 'abcdef123gh01yz' | sed 's/^\(.*[0-9]\).*$/\1/g'
abcdef123gh01

Upvotes: 2

Related Questions