linux正则表达式

来源:互联网 发布:芝华数据 编辑:程序博客网 时间:2024/06/05 02:28

规则表达式:

^  #锚定行的开始 如:'^grep'匹配所有以grep开头的行。    

$  #锚定行的结束 如:'grep$'匹配所有以grep结尾的行。    

.  #匹配一个非换行符的字符 如:'gr.p'匹配gr后接一个任意字符,然后是p。    

*  #匹配零个或多个先前字符 如:'*grep'匹配所有一个或多个空格后紧跟grep的行。    

.*   #一起用代表任意字符。   

 .   表示一个任意的字符
* 表示前一个字符有重复0或者多次
那么.*就表示任意字符重复任意多次包括0次

[]   #匹配一个指定范围内的字符,如'[Gg]rep'匹配Grep和grep。    

[^]  #匹配一个不在指定范围内的字符,如:'[^A-FH-Z]rep'匹配不包含A-R和T-Z的一个字母开头,紧跟rep的行。    

\(..\)  #标记匹配字符,如'\(love\)',love被标记为1。    

\<      #锚定单词的开始,如:'\<grep'匹配包含以grep开头的单词的行。    

\>      #锚定单词的结束,如'grep\>'匹配包含以grep结尾的单词的行。    

x\{m\}  #重复字符x,m次,如:'0\{5\}'匹配包含5个o的行。    

x\{m,\}  #重复字符x,至少m次,如:'o\{5,\}'匹配至少有5个o的行。    

x\{m,n\}  #重复字符x,至少m次,不多于n次,如:'o\{5,10\}'匹配5--10个o的行。   

\w    #匹配文字和数字字符,也就是[A-Za-z0-9],如:'G\w*p'匹配以G后跟零个或多个文字或数字字符,然后是p。   

\W    #\w的反置形式,匹配一个或多个非单词字符,如点号句号等。   

\b    #单词锁定符,如: '\bgrep\b'只匹配grep。  

正则表达式放到双引号中或者单引号中都可以

例一:

[root@Slave2 zh]# find . -regex ".*b.*3"
./Python-3.4.0/Modules/zlib/zlib.3
./Python-3.4.0/Modules/_ctypes/libffi/man/ffi_call.3
./Python-3.4.0/Modules/_ctypes/libffi/man/ffi_prep_cif_var.3
./Python-3.4.0/Modules/_ctypes/libffi/man/ffi.3
./Python-3.4.0/Modules/_ctypes/libffi/man/ffi_prep_cif.3
./Python-3.4.0/Lib/sqlite3
./Python-3.4.0/Lib/lib2to3
./Python-3.4.0/Lib/test/namespace_pkgs/project3
./Python-3.4.0/Lib/test/cfgparser.3
./Python-3.4.0/Lib/plat-next3
./ipython-5.3.0/build/scripts-3.4/ipython3
./ipython-5.3.0/build/scripts-3.4/iptest3
[root@Slave2 zh]# find . -regex '.*b.*3'
./Python-3.4.0/Modules/zlib/zlib.3
./Python-3.4.0/Modules/_ctypes/libffi/man/ffi_call.3
./Python-3.4.0/Modules/_ctypes/libffi/man/ffi_prep_cif_var.3
./Python-3.4.0/Modules/_ctypes/libffi/man/ffi.3
./Python-3.4.0/Modules/_ctypes/libffi/man/ffi_prep_cif.3
./Python-3.4.0/Lib/sqlite3
./Python-3.4.0/Lib/lib2to3
./Python-3.4.0/Lib/test/namespace_pkgs/project3
./Python-3.4.0/Lib/test/cfgparser.3
./Python-3.4.0/Lib/plat-next3
./ipython-5.3.0/build/scripts-3.4/ipython3
./ipython-5.3.0/build/scripts-3.4/iptest3
正则表达式放到双引号中或者单引号中都可以


第二个例子

[root@Slave2 test1]# cat test1.txt | grep '[a-z]\{7,\}'

afwqerr
nfasdfa
msafadsf
[root@Slave2 test1]
# cat test1.txt | grep "[a-z]\{7,\}"
afwqerr
nfasdfa
msafadsf
[root@Slave2 test1]# grep "[a-z]\{7,\}" *.txt
test1.txt:afwqerr
test1.txt:nfasdfa
test1.txt:msafadsf

0 0
原创粉丝点击