与egrep正则表达式匹配的部分

与egrep正则表达式匹配的部分

本文介绍了与egrep正则表达式匹配的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



使用egrep((GNU grep)2.5.1),我想知道是否可以选择一部分匹配的文本。 >  grep'^([a-zA-Z .-] +)[0-9] +'./file.txt 

因此,我只得到了与括号中相匹配的部分,如

  house.com 

而不是像我通常得到的那样:

  house.com112 

假设我在我的file.txt中有一行与house.com112。



(其实这个正则表达式只是一个例子,我只想知道我是否只能打印一个)



我知道在某些语言中,比如PHP,Perl甚至AWK我都可以,但我不知道我是否可以用egrep 。

预先感谢您! 使用<$ c $

  grep'^ sed 在grep找到匹配的行后修改结果。 [a-zA-Z .-] + [0-9] +'./file.txt | sed's / [0-9] \ + $ //'

或者如果您想要

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


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!

解决方案

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.-]+'

这篇关于与egrep正则表达式匹配的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:42