Match parts in regex with egrep

I was wondering if with egrep ((GNU grep) 2.5.1) I can select a piece of matching text, for example:

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

So, I get only the part that is mapped between the brackets, something like

house.com

Instead of the whole line, as I usually get:

house.com112

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

(Actually this regex is just an example that I just want to know if I can print only part of the entire line.)

I know some languages ​​like PHP, Perl or even AWK that I can, but I don’t know if I can with egrep.

Thank you in advance!

+5
source share
4 answers

sed, , grep , :

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

grep, grep -o sed:

grep '^[a-zA-Z.-]+[0-9]+' ./file.txt | grep -o '[a-zA-Z.-]+'
+10

, , + - , [0-9] + ( Paul). (, , TLD), .

ack, grep perl. , , , perl, ack.

Edit:

? , ? , egrep .

, , : , , -o .

+3

you can try using the -o, -w flags in grep. egrep is out of date, so use grep -E.

$ echo "test house.com house.com112"| grep -Eow "house.com"
house.com

The basic idea is to go through every word and check equality.

$ echo "test house.com house.com112"| awk '{for(i=1;i<=NF;i++){ if($i=="house.com") print $i}}'
house.com
+3
source

Use "lookahead" from normal

$ echo 'house.com112' | grep -Po '([a-zA-Z.]+)(?=\d+)'
house.com
+1
source

Source: https://habr.com/ru/post/1733625/


All Articles