linux 正則表示式工具
阿新 • • 發佈:2018-12-23
2006-09-02
1.grep & egrep
[[email protected] ~]$ vi test1
line 1
hello, I'm line 2
line 3
this is line 4
儲存
[[email protected] ~]$ cat test1 | grep hello hello, I'm line 2 [[email protected] ~]$ grep hello < test1 hello, I'm line 2 [[email protected] ~]$ grep hello test1 hello, I'm line 2
grep不支援+,故不顯示結果
[[email protected] ~]$ grep '^.+line [0-9]$' test1
[[email protected] ~]$ egrep '^.+line [0-9]$' test1
hello, I'm line 2
this is line 4
使用-v反轉輸出
[[email protected] ~]$ grep '^line' test1 line 1 line 3 [[email protected] ~]$ grep -v '^line' test1 hello, I'm line 2 this is line 4
- sed 流編輯器,接受輸入流並加以修改,可以修改標準輸入流 使用管道將文字做為輸入.
s表示替換,”/”表示分隔符,”“表示轉義符g表示儘可能多的匹配,預設是一行只匹配第一個.下面的sed命令將l替換為空
[[email protected] ~]$ echo "hello" | sed 's/l//g'
heo
-n引數讓sed不顯示輸出,用p選項列印匹配的行,下面的命令為了找到IP地址 [[email protected] ~]$ /sbin/ifconfig eth0 | sed -n ‘/inet addr/p’ inet addr:192.168.0.200 Bcast:192.168.255.255 Mask:255.255.0.0
匹配.*inet addr:開頭的行,將接下來的字串匹配任何非空格的部分,用向前引用引數1 “1”列印,得到IP
[[email protected] ~]$ /sbin/ifconfig eth0 | sed -n 's/.*inet addr:([^ ]*).*/1/p'
192.168.0.200
3.awk 可以完成sed可以完成的所有事情,而且更強大,通常用作cut命令的豪華版本.
列印所有使用者名稱
[[email protected] ~]$ cut -d: -f1 /etc/passwd
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
....
-d 定義分隔符為”:”, -f1列印第一個欄位.
用awk做同樣的事情:
[[email protected] ~]$ awk -F: '{print $1}' /etc/passwd
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
......
-F過載分隔符為”:”, {Print $1}是一個awk程式.
cut只能匹配單個分隔符,awk可以匹配多個空格和tab. 如要列印程序號:
[[email protected] ~]$ ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 Aug29 ? 00:00:00 init [5]
root 2 1 0 Aug29 ? 00:00:00 [ksoftirqd/0]
root 3 1 0 Aug29 ? 00:00:00 [events/0]
[[email protected] ~]$ ps -ef | awk '{print $2}'
PID
1
2
3
如非註明轉載, 均為原創. 本站遵循知識共享CC協議,轉載請註明來源