Husdup Bogdan
Husdup Bogdan

Reputation: 113

extract substring until first digit

I have the following string:

test1234a or test1234 for example and I want to extract only test from that string.

I tried the follwing

echo "Test12h" | sed -e 's/[0-9]\*$//' but is not working. 

Is there any possibility to extract the substring until first digit?

Please let me know what I miss.

Thank you

Upvotes: 4

Views: 2182

Answers (4)

oguz ismail
oguz ismail

Reputation: 50750

The proper tool for extracting substrings matching a regexp from a command's output is grep. Like,

echo "Test12h" | grep -o '^[^[:digit:]]*'

will output Test.

If Test12h is in a variable, you don't even need external utilities; parameter expansions can easily handle that, e.g:

var='Test12h'
echo "${var%%[[:digit:]]*}"

Upvotes: 7

markp-fuso
markp-fuso

Reputation: 34444

If the source happens to reside in a variable you can use parameter substitution, eg:

$ for test in test1234a test1234 Test12h
do
    echo "${test} => ${test//[0-9]*/}"
done
test1234a => test
test1234 => test
Test12h => Test

Where the general format is: ${var//Pattern/Replacement}; in the above:

  • var == test
  • Pattern == [0-9]* (first occurrence of a digit and then everything that follows
  • Replacement == '' (nothing, empty string)

So we end up stripping off everything after the first occurrence of a number.

Upvotes: 4

KamilCuk
KamilCuk

Reputation: 141030

You made a small error in your try:

echo "Test12h" | sed -e 's/[0-9].*$//'    # will output Test

The \* expects a real * in the input:

echo "Test1*" | sed -e 's/[0-9]\*$//'     # will output Test

The .* matches any number of any characters.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133518

Could you please try following.

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

OR

sed 's/[0-9][0-9a-zA-Z]*//' Input_file

Upvotes: 6

Related Questions