环境运维

shell字符截取之awk命令

1. 命令格式

awk '条件1{动作1} 条件2{动作2}...' 文件名
1
条件

一般使用关系表达式作为条件
x>6:判断x是否大于6
x>=6:是否大于等于6
1
2
3
动作

格式化输出
流程控制语句(for循环、if语句)
1
2
2. 练习:

print与printf

[root@catyuan ~]# vim student
id      name    age     sex      ##写这个表时,中间的间隔使用tab,不能使用空格
1       张三    12      男
2       李四    15      男      
3       小雪    16      女
4       小敏    18      女
[root@catyuan ~]# awk '{printf $2 "\t" $4 "\n"}' student
name    sex
张三        男
李四        男
小雪        女
小敏        女
[root@catyuan ~]# awk '{print $2 "\t" $4}' student    #print自动换行
name    sex
张三        男
李四        男
小雪        女
小敏        女
[root@catyuan ~]# awk '{printf $2 "\t" $4 }' student
name    sex张三    男李四    男小雪    女小敏    女
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
awk与cut

[root@catyuan ~]# df -h | cut -f 5 
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        20G  3.8G   16G  20% /
devtmpfs        898M     0  898M   0% /dev
tmpfs           912M     0  912M   0% /dev/shm
tmpfs           912M  9.1M  903M   1% /run
tmpfs           912M     0  912M   0% /sys/fs/cgroup
/dev/sda1       197M  152M   45M  78% /boot
tmpfs           183M  4.0K  183M   1% /run/user/42
tmpfs           183M   32K  183M   1% /run/user/0

[root@catyuan ~]# df -h | awk '{print $5 }' 
Use%
20%
0%
0%
1%
0%
78%
1%
1%

只要第一行第五列的数据
[root@catyuan ~]# df -h | grep "/dev/sda3" | awk '{print $5}'
20%
截取上面结果中的数字
[root@catyuan ~]# df -h | grep "/dev/sda3" | awk '{print $5}' | cut -f 1 -d "%"
20

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
3. BEGIN(条件)

在所有内容之前先执行BEGIN后面的内容
1
练习:

[root@catyuan ~]# awk 'BEGIN{print "test"}{print $1 "\t" $2}' student 
test
id    name
1    张三
2    李四
3    小雪
4    小敏
1
2
3
4
5
6
7
4. END

[root@catyuan ~]# awk 'END{print "test"}{print $1 "\t" $2}' student 
id    name
1    张三
2    李四
3    小雪
4    小敏
test
1
2
3
4
5
6
7
5. FS内置变量

指定分隔符
1
练习:

[root@catyuan ~]# cat /etc/passwd | grep /bin/bash
root:x:0:0:root:/root:/bin/bash
redhat:x:1000:1000:redhat:/home/redhat:/bin/bash
test1:x:1001:1001::/home/test1:/bin/bash
test2:x:1002:1002::/home/test2:/bin/bash
[root@catyuan ~]# cat /etc/passwd | grep /bin/bash | awk '{FS=":"}{print $1 "\t" $4}'
root:x:0:0:root:/root:/bin/bash          ##awk先读数据,在执行条件
redhat    1000
test1    1001
test2    1002
[root@catyuan ~]# cat /etc/passwd | grep /bin/bash | awk 'BEGIN{FS=":"}{print $1 "\t" $4}'
root    0
redhat    1000
test1    1001
test2    1002
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
6. 关系运算符

>、>=、<、<=
1
[root@catyuan ~]# cat student 
id      name    age     sex     
1       张三    12      男
2       李四    15      男      
3       小雪    16      女
4       小敏    18      女
[root@catyuan ~]# cat student | grep -v name | awk '$3>=15{print $2 }'
李四
小雪
小敏
————————————————
原文链接:https://blog.csdn.net/qq_42816766/article/details/92759951