Linux provides grep
for text filtering. But in some situations we may need more extended tool to match given pattern in given text files. This tool is called Extended Global Regular Expression Print
or simply egrep
. egrep
provides extended features over regular grep
tool.
Linux提供grep
进行文本过滤。 但是在某些情况下,我们可能需要更多扩展的工具来匹配给定文本文件中的给定模式。 该工具称为Extended Global Regular Expression Print
或简称为egrep
。 egrep
提供了比常规grep
工具更多的扩展功能。
句法 (Syntax)
Syntax of egrep
command is like below.
egrep
命令的语法如下。
egrep FLAG REGEX FILE
- `FLAG` is used to change some behaivour of `egrep`command. FLAG用于更改egrep命令的某些行为。
- `REGEX` is the pattern we want to search in regex format. REGEX是我们要以正则表达式格式搜索的模式。
- `FILE` is the file name we will search in FILE是我们要搜索的文件名
通常搜索(Search Normally)
We can use egrep
to search normal text without providing regular expression. We just need provide the term we want to search. In this example we will search ismail
in the file named /etc/passwd
.
我们可以使用egrep
来搜索普通文本,而无需提供正则表达式。 我们只需要提供我们要搜索的术语即可。 在此示例中,我们将在名为/etc/passwd
的文件中搜索ismail
。
$ egrep ismail /etc/passwd
![Search Normally](https://i-blog.csdnimg.cn/blog_migrate/5211ebab87b4fd641b186695b18a222b.png)
匹配行包含数字字符(Match Lines Contains Numeric Characters)
We can specify numeric characters by using [0-9]
which means one of numeric value from 0 to 9.
我们可以使用[0-9]
来指定数字字符,这表示从0到9的数字值之一。
$ egrep '[0-9]'/etc/passwd
匹配行包含字母字符 (Match Lines Contains Alphabet Characters)
We can also specify alphabet characters with [a-z]
for lowercase characters and [A-Z]
for uppercase characters. In this example we will match upper case characters.
我们还可以指定字母字符,其中[az]
代表小写字符, [AZ]
代表大写字符。 在此示例中,我们将匹配大写字符。
$ egrep '[A-Z]'/etc/passwd
![Match Lines Contains Alphabet Characters](https://i-blog.csdnimg.cn/blog_migrate/89f50c68241aaecf473913c35bca0af4.png)
匹配所有以字母开头的行(Match All Lines Starting with Alphabet)
We can match the start of the lines with ^
sign. In this example we will look all lines where starts with alpha character.
我们可以用^
符号匹配行的开头。 在此示例中,我们将查找所有以字母字符开头的行。
$ egrep '^[a-Z]' myinput.py
![Match All Lines Starting with Alphabet](https://i-blog.csdnimg.cn/blog_migrate/ec84fd8d0f0d07b3a5146af537919512.png)
匹配所有以数字结尾的行(Match All Lines Ending with Numeric)
We can specify the end of line with $
sign. Following command will list all lines those ends with a numeric character.
我们可以用$
符号指定行尾。 以下命令将列出所有以数字结尾的行。
$ egrep '[0-9]$' myinput.py
区分大小写 (Match Caseinsenstive)
egrep
is case senstive by default. Case sensitive means upper and lower case characters will be different like A
is different than a
. We can made our match caseinsensitive if we want with -i
option as flag. Following example will match all of following words
egrep
默认情况下区分大小写。 区分大小写意味着大写和小写字符将有所不同,例如A
不同于a
。 如果希望使用-i
选项作为标志,可以使匹配不区分大小写。 以下示例将匹配以下所有单词
- IsmaiL伊斯迈尔
- ismAILmA
- ISMAIL 伊萨尔
$ egrep -i 'ismail' myinput.py
翻译自: https://www.poftut.com/linux-egrep-command-tutorial-examples/