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!
The egrep command treats the meta-characters as they are and do not require to be escaped as is the case with grep.
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>
-v means "invert the match" in grep, in other words, return all non matching lines.
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.
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.-]+'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With