正則表示法 (regular expression)
用從文件中查找特定字符串的一種表示方法,與通配符不同,按行處理
不同編碼方式會影響正則查找的結(jié)果
- LANG=C 時(shí):0 1 2 3 4 ... A B C D ... Z a b c d ...z
-
LANG=zh_TW 時(shí):0 1 2 3 4 ... a A b B c C d D ... z Z
使用特殊符號可以在不同編碼下保證正則的有效性
正則表達(dá)式-symbol.png
符號說明
-
*
表示0個(gè)或無數(shù)個(gè)其前面的字符 -
^
行開頭符, 在[]
中的^
表示非,$
行結(jié)尾符 - 特殊字符使用
\
轉(zhuǎn)為普通字符處理
基礎(chǔ)正則表示練習(xí)
使用grep
工具,在test文件中查找
- 搜尋特定字符串:
grep -n 'the' test
- 反向選擇:
grep -vn 'the' test
- 不區(qū)分大小寫:
grep -in 'the' test
- 使用
[]
:grep -n 't[ea]st' test
, []中代表一個(gè)字符 - 反向選擇:
grep -n '[^g]oo' test
搜尋oo前不是g的字符串 - 取得沒有數(shù)字的行:
grep -n '[^0-9]' test
- 使用特殊符號代替:
grep -n '[^[:digit:]]' test
加強(qiáng)通用性 - 首列定位:
grep '^the' test
test中第一個(gè)詞是the的行 - 尾列定位:
grep '\.$' test
顯示末尾是.的行,由于.是特殊符號,因此用\轉(zhuǎn)化為普通字符 - 列出空行:
grep '^$' test
- 表示任一字符:
grep 'g..d' test
代替了中間兩個(gè)字符 - 表示0個(gè)或多個(gè)重復(fù)的字符
grep 'oo*' test
至少1個(gè)o,最多無數(shù)個(gè)o - 讀取限定范圍內(nèi)的連續(xù)字符
grep 'go\{2,5\}' test
以g開頭后面有2-5個(gè)o的會被顯示
延伸正則表示
grep -e
-
+
: 重復(fù)一次或者n次 -
?
: 0個(gè)或1個(gè) -
|
: 用或(or)的方法搜尋 -
()
: 括號中內(nèi)容作為一組搜尋 -
()+
: 多個(gè)重復(fù)群組搜尋
實(shí)用工具
sed: 取代、刪除、新增、擷取(整行處理)
- 刪除:
cat test | sed '2,5d'
刪除2-5行 - 插入:
cat test | sed '2a drink tea'
在第二行下插入字符,i:在之上插入 - 取代(行):
cat test | sed '2,5c NO number2-5'
將2-5行刪除,并插入No number - 取代(部分):
sed 's/要被取代的字串/新的字串/g'
對一行中的內(nèi)容進(jìn)行取代,結(jié)合其他管線命令使用 - 顯示:
cat test | sed -n '2,5p'
需要加上-n選項(xiàng) - 直接修改文檔:
sed -i '3d' test
刪除test文檔中的第3行
printf: 格式化輸出 printf 'format' 'content'
awk: 將一行的內(nèi)容分成數(shù)個(gè)欄位,根據(jù)分隔符,條件來處理
- 格式:
awk '條件類型1{動作1} 條件類型2{動作2} ...' filename
例子:awk '{print $1 "\t" $3}' last.txt
- $1, $2, $3...為變量,分別儲存了1,2,3欄位的內(nèi)容 $0存儲了當(dāng)前行整行的內(nèi)容
- 內(nèi)置變量:NF:每行擁有的總欄位數(shù),NR目前處理的行數(shù),F(xiàn)S分割字符(默認(rèn)為space)
- 支持運(yùn)算符:
+ - * /
邏輯符< > <= >= ==
檔案比對工具:diff cmp patch
-
diff
用在ascii純文字檔案的比較 -
cmp
用來比對非文字檔案,以字節(jié)為單位比對文件的二進(jìn)制碼(牛x) -
patch
與diff配合使用,更新或恢復(fù)文檔diff -Naur oldfile newfile > file.patch
test
"Open Source" is a good mechanism to develop programs.
apple is my favorite food.
Football game is not use feet only.
this dress doesn't fit me.
However, this dress is about $ 3183 dollars.^M
GNU is free air not free beer.^M
Her hair is very beauty.^M
I can't finish the test.^M
Oh! The soup taste good.^M
motorcycle is cheap than car.
This window is clear.
the symbol '*' is represented as start.
Oh! My god!
The gd software is a library for drafting programs.^M
You are the best is mean you are the no. 1.
The world <Happy> is the same with "glad".
I like dog.
google is the best tools for search keyword.
goooooogle yes!
go! go! Let's go.
# I am VBird