Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

awk 正則表達式完整指南:ERE 語法、運算符與內建函數實戰

編輯:Linux 教學

awk 採用 擴展正則表達式,語法與 grep -E、JavaScript、Java、.NET 相容。掌握 ERE 核心元字符,即能靈活處理複雜文字匹配。

ERE 核心元字符速查表

符號說明範例
.任意單一字符(含換行)/a..e/ 匹配 a??e
*前導字符 0 次或多次/a.*e/ 匹配 a...e
+前導字符 1 次或多次/smith+ern/ 匹配 smithhern
?前導字符 0 次或 1 次/smith?/ 匹配 smit 或 smith
{m}精確 m 次/l{2}/ 匹配 ll
{m,}至少 m 次/t{2,}/ 匹配 tt, ttt...
{m,n}m 到 n 次/er{1,2}/ 匹配 er, err
[abc]字符集合/sm[a-h]/ 匹配 sma-smh
[^abc]排除字符集合/sm[^a-h]/ 排除 sma-smh
|或邏輯/allen|alan/ 匹配 allen 或 alan
()分組/a(ll)?(nn)?e/ 匹配 ae, alle, anne
^行首/字符串開頭$2 ~ /^h/ 欄位 2 以 h 開頭
$行尾/字符串結尾$2 ~ /y$/ 欄位 2 以 y 結尾
\轉義/a\/\// 匹配 a//

注意:ERE 不支援 \d \D \s \S \w \W \b \B 等 Perl 風格簡寫,需用字符集合替代(如 [0-9] 代替 \d)。

awk 中三種正則呼叫方式

1. 模式匹配動作

awk '/REG/{action}'        # $0 匹配 REG 才執行 action
awk '$1 ~ /^root$/'        # 第 1 欄位精確匹配 root

2. 正則運算符 ~ / !~

awk 'BEGIN{info="test"; if(info ~ /test/) print "ok"}'

3. 內建正則函數

函數用途
gsub(ere, repl, [in])全域替換,返回替換次數
sub(ere, repl, [in])首次替換,返回 0/1
match(str, ere)返回匹配位置,設定 RSTART/RLENGTH
split(str, arr, [ere])依正則分割字符串到陣列

實戰範例

全域替換數字為 !

awk 'BEGIN{info="test2010test"; gsub(/[0-9]+/,"!",info); print info}'
# 輸出: test!test!

查找子字符串位置

awk 'BEGIN{info="hello world"; print index(info,"world")}'
# 輸出: 7 (未找到回傳 0)

正則匹配位置與長度

awk 'BEGIN{info="test2010"; match(info,/[0-9]+/); print RSTART, RLENGTH}'
# 輸出: 5 4 (從第 5 字符起長度 4)

分割字符串

awk 'BEGIN{info="a:b:c"; split(info,arr,":"); for(i in arr) print i,arr[i]}'
# 輸出: 1 a / 2 b / 3 c (順序不保證)

三大正則流派差異速查

特性BRE (grep/sed)ERE (awk/egrep)PRE (perl/grep -P)
+ ? | { } ( )需轉義 \+ \? \| \{ \} \( \)直接使用直接使用
\d \s \w \b不支援不支援支援
非貪婪 *? +?不支援不支援支援
反向引用 \1支援不支援 (gawk 4.1+ 支援)支援

選擇工具時:簡單行匹配用 grep,欄位處理用 awk,複雜替換用 sed,極致功能用 perl。

Copyright © Windows教程網 All Rights Reserved