awk 获取指定字符,cut截取某字符以前内容

 

转载:https://blog.csdn.net/qq_42816766/article/details/92759951

命令格式

awk '条件1{动作1} 条件2{动作2}...' 文件名
  •  
一般使用关系表达式作为条件
x>6:判断x是否大于6
x>=6:是否大于等于6
  •  

动作

格式化输出
流程控制语句(for循环、if语句)

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张三	男李四	男小雪	女小敏	女

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

3. BEGIN(条件)

在所有内容之前先执行BEGIN后面的内容

练习:

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

4. END

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

5. FS内置变量

指定分隔符

练习:

[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

6. 关系运算符

>、>=、<、<=
[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 }'
李四
小雪
小敏

Guess you like

Origin blog.csdn.net/weixin_43841155/article/details/109511418
awk