9.6/9.7 awkhtml
幾種用法bash
awk '{print $1}' 1.txt \\輸出第一列 awk -F ':' '{print $1,$3,$5}' test.txt \\指定分隔符:輸出1,3,5列 awk -F ':' '{print $1"#"$3"#"$5}' test.txt awk '/oo/' test.txt awk -F ':' "$1 ~ /oo/' test.txt awk -F ':' '$1 ~ /oo+/' test.txt awk -F ':' '$1 ~ /o+/' test.txt awk -F ':' '/root/ {print $1,$3} /user/ {print $3,$4}' test.txt awk -F ':' '/root/ {print $1,$3} /user/ {print $1,$3,$4}' test.txt awk -F ':' '$3==0' test.txt awk -F ':' '$3>=1000 {print $0}' test.txt awk -F ':' '$7!="/sbin/nologin" {print $0}' test.txt
egpost
root@lixiang01:~# awk -F ':' '{print $1,$3,$5}' test.txt | head -2 root 0 root bin 1 bin
awk -F 指定分隔符 print中的都好打印爲空格,其餘分隔符不變code
root@lixiang01:~# awk -F ':' '{print $1"#"$3"#"$5}' test.txt | head -2 root#0#root bin#1#bin
awk的正則匹配與sed的相似htm
root@lixiang01:~# awk '/oo/' test.txt root:x:0:0:root:/root:/bin/bash lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin mail:x:8:12:mail:/var/spool/mail:/sbin/nologin operator:x:11:0:operator:/root:/sbin/nologin postfix:x:89:89::/var/spool/postfix:/sbin/nologin
root@lixiang01:~# awk -F ':' '$1 ~ /oo/' test.txt root:x:0:0:root:/root:/bin/bash
root@lixiang01:~# awk -F ':' '$1 ~ /o+/' test.txt |head -2 root:x:0:0:root:/root:/bin/bash daemon:x:2:2:daemon:/sbin:/sbin/nologin
awk匹配能夠屢次執行get
root@lixiang01:~# awk -F ':' '/root/ {print $1,$3} /user/ {print $1,$3,$4}' test.txt root 0 operator 11 tss 59 59 user1 1001 1001 user2 1002 1006 user3 1004 1005 root@lixiang01:~# grep -E 'root|user' test.txt
root:x:0:0:root:/root:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin user1:x:1001:1001::/home/user1:/bin/bash user2:x:1002:1006::/home/user2:/bin/bash user3:x:1004:1005::/home/user3:/bin/bash
awk的匹配可使用「|」用爲或者,{print $0}爲默認輸出,可省test
root@lixiang01:~# awk -F ':' '/root|user/ {print $0}' test.txt root:x:0:0:root:/root:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin user1:x:1001:1001::/home/user1:/bin/bash user2:x:1002:1006::/home/user2:/bin/bash user3:x:1004:1005::/home/user3:/bin/bash
比較數字時不能加雙引號awk
root@lixiang01:~# awk -F ':' '$3>=1000' test.txt lixiang:x:1000:1000::/home/lixiang:/bin/bash user1:x:1001:1001::/home/user1:/bin/bash user2:x:1002:1006::/home/user2:/bin/bash user3:x:1004:1005::/home/user3:/bin/bash axiang:x:1010:1011::/home/axiang:/bin/bash root@lixiang01:~# awk -F ':' '$3>="1000"' test.txt | head -3 daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
root@lixiang01:~# awk -F ':' '$7!="/bin/bash"' test.txt bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
擴展 把這裏面的全部練習題作一下 http://www.apelearn.com/study_v2/chapter14.html擴展