Regular Expressions include basic regular expressions and extended regular expressions.
In general, grep uses a basic regular expression. To use an extended regular expression, you can use the-E Option, equivalent to egrep.
Other grep options:
-A n: displays the N rows after the matching row (after ).
-B N: displays n rows (Before) before the matching row ).
-C n: N rows before and after the display. (Context)
Example 1:
[[email protected] tmp]# grep --color -A 1 ‘^cpu MHz‘ /proc/cpuinfo cpu MHz : 2392.390cache size : 3072 KB[[email protected] tmp]#
[[email protected] tmp]# grep --color -A 1 -B 2 ‘^cpu MHz‘ /proc/cpuinfo model name : Intel(R) Core(TM) i3-2370M CPU @ 2.40GHzstepping : 7cpu MHz : 2392.390cache size : 3072 KB[[email protected] tmp]#
[[email protected] tmp]# grep --color -C 2 ‘^cpu MHz‘ /proc/cpuinfo model name : Intel(R) Core(TM) i3-2370M CPU @ 2.40GHzstepping : 7cpu MHz : 2392.390cache size : 3072 KBfpu : yes[[email protected] tmp]#
Extended regular expression:
The metacharacters used in the extended regular expression are basically the same as those in the basic regular expression. The main differences are as follows:
+: Match the previous character once or multiple times.
{N, m}: the first character appears n to m times.
|: Represents or. For example, a | B Indicates matching A or B.
(): Indicates the group, which does not require backslash.
Example:
[[email protected] tmp]# grep -E ‘(C|c)at‘ aacatCat[[email protected] tmp]#
Number of matching values from 1 to 25:
grep -E --color ‘\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b‘
View IP information:
[[email protected] ~]# ifconfig bond0 | grep ‘inet addr‘ | grep -E --color -o ‘(\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.\b){3}\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b‘ 172.17.100.252172.17.100.255255.255.255.0[[email protected] ~]#
This article is from the "Hezhang" blog, please be sure to keep this source http://hezhang.blog.51cto.com/1347601/1435168