Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parts of a match in regular expression with egrep

Tags:

regex

grep

I was wondering if, with egrep ((GNU grep) 2.5.1), I can select a part of the matched text, something like:

grep '^([a-zA-Z.-]+)[0-9]+' ./file.txt

So I get only the part which matched, between the brackets, something like

house.com

Instead of the whole line like I usually get:

house.com112

Assuming I have a line with house.com112 in my file.txt.

(Actually this regular expression is just an example I just want to know if I can print only a part of the whole line.)

I do know in some languages, such as PHP, Perl or even AWK I can, but I do not know if I can with egrep.

Thank you in advance!

like image 209
José M. Gilgado Avatar asked Feb 20 '10 00:02

José M. Gilgado


People also ask

What does egrep command do?

The egrep command treats the meta-characters as they are and do not require to be escaped as is the case with grep.

What is egrep pattern?

egrep is an acronym for "Extended Global Regular Expressions Print". It is a program which scans a specified file line by line, returning lines that contain a pattern matching a given regular expression. The standard egrep command looks like: egrep <flags> '<regular expression>' <filename>

What does egrep V mean?

-v means "invert the match" in grep, in other words, return all non matching lines.

Can you use regex with grep?

GNU grep supports three regular expression syntaxes, Basic, Extended, and Perl-compatible. In its simplest form, when no regular expression type is given, grep interpret search patterns as basic regular expressions. To interpret the pattern as an extended regular expression, use the -E ( or --extended-regexp ) option.


1 Answers

Use sed to modify the result after grep has found the lines that match:

grep '^[a-zA-Z.-]+[0-9]+' ./file.txt | sed 's/[0-9]\+$//'

Or if you want to stick with only grep, you can use grep with the -o switch instead of sed:

grep '^[a-zA-Z.-]+[0-9]+' ./file.txt | grep -o '[a-zA-Z.-]+'
like image 179
Mark Byers Avatar answered Oct 09 '22 17:10

Mark Byers