Regex 正規表示式

教學網站

基本搜尋

# 搜尋字串區分大小寫
echo "This is a test" | sed -n '/test/p'
echo "This is a test" | awk '/test/{print $0}'

# 可以包含空白與數字
echo "This is a test 2 again" | awk '/test 2/{print $0}' 

特殊字元
字元:.*[]^${}\+?|()

$ cat myfile
There is 10$ on my pocket

awk '/\$/{print $0}' myfile

echo "\ is a special character" | awk '/\\/{print $0}' 

echo "This ^ is a test" | sed -n '/s ^/p'

搜尋字首與字尾

# 搜尋字首
$ echo "likegeeks website" | awk '/^likegeeks/{print $0}'

# 搜尋字尾
$ echo "This is a test" | awk '/test$/{print $0}' 

# 搜尋相同字元行的文字
$ awk '/^this is a test$/{print $0}' myfile

# 不顯示空白行
$ awk '!/^$/{print $0}' myfile

搜尋字元
用 dot

# cat myfile
this is a test
This is another test
And this is one more
start with this

# awk '/.st/{print $0}' myfile
this is a test
This is another test

用 [ ]

// 包含 oth 與 ith
$ awk '/[oi]th/{print $0}' myfile
This is another test
start with this

// 不包含 oth 與 ith
$ awk '/[^oi]th/{print $0}' myfile
And this is one more
start with this                  <== 有兩個 th

使用範圍

$ awk '/[e-p]st/{print $0}' myfile
this is a test
This is another test

$ echo "123" | awk '/[0-9][0-9][0-9]/'

$ awk '/[a-fm-z]st/{print $0}' myfile
this is a test
This is another test