Linux系列:shell編程之文檔操作(3)
一、正則表達式和通配符
// 本章知識點講解文件如下:文件格式不要動,就是這樣。 [root@image1 ~]# cat test_rule.sh Mr. Zhang San said; he was the hones man in LampBrother. 123despise him. But since Mr. Li Si came, he never saaaid those words. 5555nice! because, actuaaaally, Mr. Li Si is the most honest man Later, Mr. Zhang San soid his hot body.
1)linux中支持的通配符
* 代表任意字符重復任意多次; ? 代表任意字符重復一次; [] 代表匹配[]中所寫的任意一個字符;
* 前一個字符匹配0次,或任意多次。 . 匹配除了換行符外,任意一個字符。 ^ 匹配行首。【^hello匹配以hello開頭的行】 $ 匹配行尾?!緃ello$匹配以hello結尾的行】 [] 匹配中括號中指定的任意一個字符,只匹配一個字符。 [^] 取反。匹配除中括號的字符以外的任意一個字符。 \ 轉義符。取消特殊符號的含義,變為普通字符。 \{n\} 表示其前面的字符恰好出現n次。[0-9]\{4\}匹配4位數字 \{n,\} 表示其前面的字符出現不小于n次。[0-9]\{2,\}匹配2位及以上數字 \{n,m\} 表示其前面的字符至少出現n次,最多出現m次。
// 這樣寫是匹配所有內容,包括空白行 [root@image1 ~]# grep "a*" test_rule.sh // 匹配至少有一個a的行 [root@image1 ~]# grep "aa*" test_rule.sh // 匹配最少包含兩個連續a的行 [root@image1 ~]# grep "aaa*" test_rule.sh // 匹配最少包含四個連續a的行 [root@image1 ~]# grep "aaaa*" test_rule.sh
// 匹配在s、d這兩個字母之間一定有兩個字符的單詞 [root@image1 ~]# grep "s..d" test_rule.sh Mr. Zhang San said; Later, Mr. Zhang San soid his hot body. // 匹配在s、d字母之間有在意字符 [root@image1 ~]# grep "s.*d" test_rule.sh Mr. Zhang San said; he never saaaid those words. Later, Mr. Zhang San soid his hot body. // 匹配所有內容 [root@image1 ~]# grep ".*" test_rule.sh
// 匹配以大寫“M”開頭的行 [root@image1 ~]# grep "^M" test_rule.sh Mr. Zhang San said; Mr. Li Si is the most honest man // 匹配以小寫“n”結尾的行 [root@image1 ~]# grep "n$" test_rule.sh Mr. Li Si is the most honest man // 匹配空白行。-n表示顯示匹配的是哪一行。 [root@image1 ~]# grep -n "^$" test_rule.sh 7: [root@image1 ~]#
// 匹配s和id中,有一個a或者有一個o的行 [root@image1 ~]# grep "s[ao]id" test_rule.sh Mr. Zhang San said; Later, Mr. Zhang San soid his hot body. // 匹配帶有一個數字的行 [root@image1 ~]# grep "[0-9]" test_rule.sh 123despise him. 5555nice! // 匹配不帶有一個數字的行 [root@image1 ~]# grep "[^0-9]" test_rule.sh
// 匹配不用小寫字母開頭的行 [root@image1 ~]# grep "^[^a-z]" test_rule.sh Mr. Zhang San said; 123despise him. But since Mr. Li Si came, 5555nice! Mr. Li Si is the most honest man Later, Mr. Zhang San soid his hot body. // 匹配不用字母開頭的行 [root@image1 ~]# grep "^[^a-zA-Z]" test_rule.sh 123despise him. 5555nice!
// 匹配使用“.”結尾的行 [root@image1 ~]# grep "\.$" test_rule.sh he was the hones man in LampBrother. 123despise him. he never saaaid those words. Later, Mr. Zhang San soid his hot body.
// 匹配a字母連續出現三次的字符串 [root@image1 ~]# grep "a\{3\}" test_rule.sh he never saaaid those words. because, actuaaaally, // 匹配包含連續的四個數字的字符串 [root@image1 ~]# grep "[0-9]\{4\}" test_rule.sh 5555nice!
// 匹配至少以三個連續數字開頭的字符串。 [root@image1 ~]# grep "^[0-9]\{3,\}" test_rule.sh 123despise him. 5555nice!
// 匹配在字母s和字母i之間有最少一個a,最多三個a的行 [root@image1 ~]# grep "sa\{1,3\}i" test_rule.sh Mr. Zhang San said; he never saaaid those words. // 匹配在字母s和字母i之間有最少一個a,最多兩個a的行 [root@image1 ~]# grep "sa\{1,2\}i" test_rule.sh Mr. Zhang San said;
Linux Shell
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。