正則介紹_grep
阿新 • • 發佈:2018-01-15
file 介紹 default 問號 字符 shell 同時 pre -i 9.1 正則介紹_grep(上)
grep ‘oo‘test.txt //表示0個或者多個號前面的字符//
grep ‘.‘test.txt //點*就是通配//
grep ‘o{2}‘/etc/passwd //表示一個範圍//
egrep ‘o+‘/etc/passwd //表示一個或多個加號前面的字符//
egrep ‘oo?‘/etc/passwd //表示0個或一個問號前面的字符//
egrep ‘root|nologin‘ /etc/passwd //豎線表示或者//
什麽是正則
正則是一串有規律的字符串
掌握好正則對於編寫shell腳本有很大的幫助
各種編程語言中都有正則,原理是一樣的
本章將要學習grep/egrep、sed、awk
grep
grep[-cinvABC] ‘word‘ filename
-c 行數
-i 不區分大小寫
-n 顯示行號
-v 取反
-r遍歷所有子目錄
-A 後面跟數字,過濾出符合要求的行以及下面n行
-B同上,過濾出符合要求的行以及上面n行
-c同上,同時過濾出符合要求的行以及上下各n行
[root@centos-01 ~]# ls 11.txt 123 1.txt 1.txt~ 234 2.txt 3.txt anaconda-ks.cfg.1 default [root@centos-01 ~]# mkdir grep [root@centos-01 ~]# cd grep [root@centos-01 grep]# cp /etc/passwd . [root@centos-01 grep]# ls passwd [root@centos-01 grep]# pwd /root/grep [root@centos-01 grep]# ls passwd [root@centos-01 grep]# grep ‘nologin‘ passwd [root@centos-01 grep]# grep -c ‘nologin‘ passwd //加-c看有多少行// 18 [root@centos-01 grep]# grep -n ‘nologin‘ passwd //加-n顯示行號// [root@centos-01 grep]# grep -ni ‘nologin‘ passwd //加i會把大寫的一列列出來//
9.2 grep(中)
grep ‘[0-9]‘ /etc/inittab
[root@centos-01 grep]# grep ‘[0-9]‘ passwd
grep -v‘[0-9]‘ /etc/inittab //不帶數字的行//
grep -v‘^#‘/etc/inittab //^表示以什麽開頭的行,這裏表示以#開頭的行,v表示不是以什麽開頭的行//
grep ‘^[^a-zA-Z]‘test.txt
^如果在[]中則取非的意思,如果在[ ]外面,則是以什麽什麽開頭的意思
9.3 grep (下)
grep ‘r.o‘test.txt //小數點表示任意一個字符//
grep ‘.‘test.txt //點*就是通配//
grep ‘o{2}‘/etc/passwd //表示一個範圍//
egrep ‘o+‘/etc/passwd //表示一個或多個加號前面的字符//
egrep ‘oo?‘/etc/passwd //表示0個或一個問號前面的字符//
egrep ‘root|nologin‘ /etc/passwd //豎線表示或者//
正則介紹_grep