Reputation: 113
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
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
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
== testPatter
n == [0-9]*
(first occurrence of a digit and then everything that followsReplacement
== '' (nothing, empty string)So we end up stripping off everything after the first occurrence of a number.
Upvotes: 4
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
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