Grep\Egrep\Fgrep
文本查找的需要:
grep==global research ;根據(jù)模式,搜索文本并顯示符合模式的文本行;
Pattern:文本字符和正則表達式的元字符組合而成匹配條件
grep [OPTIONS] PATTERN [FILE...]
——grep 'root' data_20220502-115757.log
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
grep
-i(忽略大小寫) grep -i 'root' /etc/passwd
--color grep --color 'root' /etc/passwd
alias grep='grep --color'
-v (顯示不符合威恼,不匹配的行) grep -v 'root' /etc/passwd
-o (只顯示被模式匹配的字符串)grep -o 'root' /etc/passwd
*任意長度的任意字符
?任意單個字符
[]:范圍內(nèi)
[^]:范圍外
正則表達式
元字符:
. 匹配任意單個字符
[]匹配指定范圍內(nèi)的任意單個字符
[^]匹配指定范圍外的任意單個字符
[:digit:][:lower:][:upper:].....
[[:digit:] ]
grep 'r..t' /etc/passwd
匹配次數(shù):
*:匹配其前面的字符任意次
a,b,ab,aab,adb,annb
ab==b,ab,aab,adb,annb(a可以出現(xiàn)也可以不出現(xiàn))
a.b=ab,aab,adb,annb
.* 任意長度的任意字符
\?匹配其前面的字符1次或者0次
a?b=b,ab,aab,adb,annb
grep 'a?b' test.text
\{m,n\}匹配其前面的字符至少m次寝并,至多n次
{1,}:至少1次箫措,多了不限制
{0,3}:至多3次
grep 'a{1,3}b' test.text= ab aab
grep 'a.{1,3}b' test.text =aab adb amnb amnbmnbmnb
位置錨定:
^錨定行首:此字符后面的任意內(nèi)容必須出現(xiàn)在行首
grep '^r' /etc/passwd
$錨定行尾:此字符后面的任意內(nèi)容必須出現(xiàn)在行尾
grep 't$' /etc/passwd
^$空白行
grep '^$' /etc/passwd
以數(shù)字結(jié)尾的行:
grep '[[:digit:]]$' /etc/inittab
以空白行+數(shù)字結(jié)尾的行:
grep '[[:space:]][[:digit:]]$' /etc/inittab
\<或者\b:錨定詞首,其后面的任意字符必須作為單詞‘首部’出現(xiàn)
<root> root出現(xiàn)
\>或者\b:錨定詞尾衬潦,其后面的任意字符必須作為單詞‘尾部’出現(xiàn)
[root@ip-10-18-6-152 logs]# grep '\<root\>' test2.txt
this is root
[root@ip-10-18-6-152 logs]# grep '\<root' test2.txt
this is root
rooter is a dog name
[root@ip-10-18-6-152 logs]# grep '\<root\b' test2.txt
this is root
[root@ip-10-18-6-152 logs]# grep '\broot' test2.txt
this is root
rooter is a dog name
分組:
()
(ab)* 后項引用
\1:第一個左括號以及與之對應(yīng)的右括號所包括的所有內(nèi)容
\2:第一個左括號以及與之對應(yīng)的
\3:第一個左括號以及與之對應(yīng)的
grep '(ab)*' test.text
Me love his lover.
She like her liker.
Me like his lover.
grep '\(l..e\).*\1' test3.txt
[root@ip-10-18-6-152 logs]# grep '\(l..e\)*r' test3.txt
Me love his lover.
She like her liker.
Me like his lover.
[root@ip-10-18-6-152 logs]# grep '\(l..e\).*\1' test3.txt
Me love his lover.
She like her liker.
以任意數(shù)字開頭并結(jié)尾的:
grep '([0-9]).*\1$' test3.txt