天天看點

awk

[root@abinlinux ~]# awk -F ':' '{print $3}' 1.txt   第三段    

1

2

[root@abinlinux ~]# awk -F ':' '{print $3,$4}' 1.txt     三段   四段    截取段  

0 0

1 1

2 2

[root@abinlinux ~]# awk -F ':' 'OFS=":" {print $3,$4}' 1.txt  

OFS=":"相當于 -F   指定分隔符   以:号分開  同時可以使用 #&! 也可以用做分開

0:0

1:1

2:2

3:4

4:7

[root@abinlinux ~]# awk -F ':' 'OFS="#" {print $3,$4,$1}' 1.txt    

$3 第三段  $4 第四段 $1第一段  

0#0#root

1#1#bin

2#2#daemon

3#4#adm

[root@abinlinux ~]# awk '/yun/' 1.txt    awk 比對 用法

yun:x:500:500::/home/yun:/bin/bash

[root@abinlinux ~]# awk '/yun|root/' 1.txt     也可以比對多個 用| 他表示  用法  awk可以直接用|

root:x:0:0:root:/root:/bin/bash

operator:x:11:0:operator:/root:/sbin/nologin

[root@abinlinux ~]# awk '/r*o/' 1.txt   可以比對*号前面的任意一個  

bin:x:1:1:bin:/bin:/sbin/nologin

[root@abinlinux ~]# awk '/r?o/' 1.txt   比對問号前面 的一個或者多個  

[root@abinlinux ~]# awk '/r+o/' 1.txt   比對一個或多個加好前面的字元  

mail:x:8:12:mail:/var/spoorrrrrrrrol/mail:/sbin/nologin

gopher:x:13:30:gopher:/var/goproher:/sbin/nologin

[root@abinlinux ~]# awk '/r.*o/' 1.txt     這叫貪婪比對  

adm:x:3:4:adm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologi

[root@abinlinux ~]# awk '/(oo)+/' 1.txt    一個是可以的多個也是可以的

rooooooooot:x:0:0:root:/root:/bin/bash

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

[root@abinlinux ~]# awk '/(ooo)+/' 1.txt      三個O隻有 這些         awk不支援{}

halt:x:7:0:halt:/sbin:/rooooo*osbin/halt

[root@abinlinux ~]# awk -F ':' '$1~/r*o/' 1.txt    比對第一段帶ro的 或者多個  

daemon:x:2:2:daemon:/sbin:/sbin/nologin

shutdown:x:6:0:shutdowr.on:/sbin:/sbin/shutdown

[root@abinlinux ~]# awk -F ':' '$1~/r*o/ {print $4}' 1.txt     比對過程中單獨的顯示第幾段

                                                                                               精準比對精準列印  

30

99

89

26

[root@abinlinux ~]# awk -F ':' '$1~/r*o/ {print $1,$3}; $1~/nobody/ {print $1,$3}' 1.txt

兩個規則的比對

rooooooooot 0

daemon 2

shutdown 6

operator 11

gopher 13

nobody 99

postfix 89

postgres 26

[root@abinlinux ~]# awk -F ':' '$1~/r*o|nobody/ {print $1,$3}' 1.txt

'$1~/r*o|nobody/  比對第一段 r*o 或者nobody      ;{print $1,$3}'  比對第一和第三段  列印

                        一個規則的比對  

本文轉自 amenging 51CTO部落格,原文連結:http://blog.51cto.com/11335852/1983968