生活随笔
收集整理的這篇文章主要介紹了
Unix/Linux 中shell命令 awk
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
shell命令awk使用例:
通過腳本打印出系統當前內存使用的百分比:
#!/bin/bash
[centos@centos shell
]$
free -mtotal used
free shared buff/cache available
Mem:
1819 508 130 11 1180 1130
Swap:
2047 368 1679
[centos@centos shell
]$
vim useCache.sh
echo "此腳本可以用來cha看當前系tong 內存使用百分比"
use=$(free -m | grep Mem: | awk '{print $3}')
total=$(free -m | grep Mem: | awk '{print $2}')
useper=$(expr $use \* 100 / $total)
echo "系tong當前內存使用百分比wei : "
echo ${useper}%
[centos@centos shell
]$
chmod +x useCache.sh
[centos@centos shell
]$ ./useCache.sh
此腳本可以用來cha看當前系tong 內存使用百分比
系tong當前內存使用百分比wei
:
27%
[centos@centos shell
]$
以空格為分隔,顯示每行有多少字段
[centos@centos shell
]$
vim file
aaaaaaaa bbbbb ccccc dddddd eeeee fffffffbbbbbbbbbb aaaaa ccccccc ddddddddd eeeeeeeeeeccccccc bbbbbbb eeeeee hhhhhhhhheeeeee ffffffffffff
[centos@centos shell
]$
awk '{print NF}' file
6
0
5
0
4
0
3
0
2
0
1
以空格為分隔,查看文件中字段數大于4的行
[centos@centos shell
]$
awk 'NF>4 {print}' file
aaaaaaaa bbbbb ccccc dddddd eeeee fffffff
bbbbbbbbbb aaaaa ccccccc ddddddddd eeeeeeeeee
[centos@centos shell
]$
顯示每一行的行號
[centos@centos shell_study
]$
awk '{print NR, $0}' file
1 aaaaaaaa bbbbb ccccc dddddd eeeee fffffff
2
3 bbbbbbbbbb aaaaa ccccccc ddddddddd eeeeeeeeee
4
5 ccccccc bbbbbbb eeeeee hhhhhhhhh
6
7 fffff hhhhhhh yyyyyyyy
8
9 eeeeee ffffff
10
11 ffffff
[centos@centos shell_study
]$
awk 'NR==5 {print}' file
ccccccc bbbbbbb eeeeee hhhhhhhhh
不顯示第一行
[centos@centos shell_study
]$ route -n
| awk 'NR!=1{print}'
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0
192.168.150.1
0.0.0.0 UG
100 0 0 ens33
192.168.122.0
0.0.0.0
255.255.255.0 U
0 0 0 virbr0
192.168.150.0
0.0.0.0
255.255.255.0 U
100 0 0 ens33
[centos@centos shell_study
]$ route -n
| awk 'NR>1{print}'
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0
192.168.150.1
0.0.0.0 UG
100 0 0 ens33
192.168.122.0
0.0.0.0
255.255.255.0 U
0 0 0 virbr0
192.168.150.0
0.0.0.0
255.255.255.0 U
100 0 0 ens33
匹配文件中包含 root 的行
[centos@centos shell_study
]$
awk -F:
'/root/' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
不匹配文件中包含 root 的行
[centos@centos shell_study
]$
awk -F:
'!/root/' /etc/passwd
匹配文件中空行的行號
[centos@centos shell_study
]$
awk '{if($0~/^$/)print NR}' file
2
4
6
8
10
不匹配文件中包含 root 的行
[centos@centos shell_study
]$
awk -F:
'!/root/' /etc/passwd
[centos@centos shell_study
]$
awk -F:
'{if($3>100)print "LARGE";else print "SMALL"}' /etc/passwd
總結
以上是生活随笔為你收集整理的Unix/Linux 中shell命令 awk的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。