6-3 9 awk

6-3 9 awk

6-3 9 awk
• 发表于 3个月前
• 阅读 6
• 收藏 0
• 评论 0

9.6/9.7 awk

``````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
``````

eg

``````root@lixiang01:~# awk -F ':' '{print \$1,\$3,\$5}' test.txt | head -2
root 0 root
bin 1 bin
``````

awk -F 指定分隔符 print中的都好打印为空格,其他分隔符不变

``````root@lixiang01:~# awk -F ':' '{print \$1"#"\$3"#"\$5}' test.txt | head -2
root#0#root
bin#1#bin
``````

awk的正则匹配与sed的类似

``````root@lixiang01:~# awk '/oo/' test.txt
root:x:0:0:root:/root:/bin/bash
``````
``````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
``````

awk匹配可以多次执行

``````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
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｝为默认输出，可省

``````root@lixiang01:~# awk -F ':' '/root|user/ {print \$0}' test.txt
root:x:0:0:root:/root:/bin/bash
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
``````

``````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
``````
``````root@lixiang01:~# awk -F ':' '\$7!="/bin/bash"' test.txt

sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
``````

×