Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract text from a string using sed?

Tags:

regex

bash

sed

My example string is as follows:

This is 02G05 a test string 20-Jul-2012 

Now from the above string I want to extract 02G05. For that I tried the following regex with sed

$ echo "This is 02G05 a test string 20-Jul-2012" | sed -n '/\d+G\d+/p' 

But the above command prints nothing and the reason I believe is it is not able to match anything against the pattern I supplied to sed.

So, my question is what am I doing wrong here and how to correct it.

When I try the above string and pattern with python I get my result

>>> re.findall(r'\d+G\d+',st) ['02G05'] >>> 
like image 313
RanRag Avatar asked Jul 19 '12 20:07

RanRag


People also ask

Can you use regex in sed?

The sed command has longlist of supported operations that can be performed to ease the process of editing text files. It allows the users to apply the expressions that are usually used in programming languages; one of the core supported expressions is Regular Expression (regex).


1 Answers

How about using grep -E?

echo "This is 02G05 a test string 20-Jul-2012" | grep -Eo '[0-9]+G[0-9]+' 
like image 132
mVChr Avatar answered Sep 24 '22 20:09

mVChr