How to extract text from a string using sed?
How about using grep -E
?
echo "This is 02G05 a test string 20-Jul-2012" | grep -Eo '[0-9]+G[0-9]+'
Try this instead:
echo "This is 02G05 a test string 20-Jul-2012" | sed 's/.* \([0-9]\+G[0-9]\+\) .*/\1/'
But note, if there is two pattern on one line, it will prints the 2nd.
The pattern \d
might not be supported by your sed
. Try [0-9]
or [[:digit:]]
instead.
To only print the actual match (not the entire matching line), use a substitution.
sed -n 's/.*\([0-9][0-9]*G[0-9][0-9]*\).*/\1/p'
sed
doesn't recognize \d
, use [[:digit:]]
instead. You will also need to escape the +
or use the -r
switch (-E
on OS X).
Note that [0-9]
works as well for Arabic-Hindu numerals.