字符截取命令-awk命令

awk命令是一个异常复杂的命令。了解常用的用法。

功能:文件中截取我们需要的数据

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

说明:

条件(Pattern)
- 一般使用关系表达式作为条件
- x>10判断变量 x是否大于10
- x>=10 大于等于10
- x<=10 小于等于10
动作(Action)
- 格式化输出
- 流程控制语句

例如:

[root@localhost home]# cat student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   70

查看文件student.txt第二列和第四列

[root@localhost home]# awk '{printf $2 "\t" $4 "\n"}' student.txt 
Name    Mark
furong  88
fengjie 60
cang    70

说明

  • awk一行一行的的读取文件
  • 判断条件,如果条件满足,则执行动作
  • 把文件名赋值给$0字段,将ID赋值给$1字段,依次类推
  • awk默认是空格或者制表符做为分隔符
  • 没有条件限制就是无条件显示执行动作
  • 仅仅是提取制表符和有规律的

示例:

[root@localhost home]# df -h | awk '{print $5}'
Use%
21%
0%
30%
1%
1%
[root@localhost home]# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda6       5.9G  1.2G  4.5G  21% /
tmpfs           491M     0  491M   0% /dev/shm
/dev/sda1       190M   54M  127M  30% /boot
/dev/sda2       9.5G   23M  9.0G   1% /home
/dev/sda5       1.9G  3.1M  1.8G   1% /usr/local
[root@localhost home]# df -h | grep "/dev/sda6" | awk '{print $%}'
awk: {print $%}
awk:         ^ syntax error
[root@localhost home]# df -h | grep "/dev/sda6" | awk '{print $5}'
21%
[root@localhost home]# df -h | grep "/dev/sda6" | awk '{print $5}' | cut -d "%" -f 1
21

示例2

[root@localhost home]# cat student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   70
[root@localhost home]# awk 'BEGIN{print "this is a test"}{print $2 "\t" $4}' student.txt 
this is a test
Name    Mark
furong  88
fengjie 60
cang    70
[root@localhost home]# awk 'END{print "this is a test"}{print $2 "\t" $4}' student.txt 
Name    Mark
furong  88
fengjie 60
cang    70
this is a test

BEGIN作用,awk默认是用空格或者制表符进行分割的。BEGIN作用是设定变量来做分隔符。如果不写BEGIN,则awk会从读取第一行后才能执行按照分隔符分割的。

[root@localhost home]# cat /etc/passwd |grep "/bin/bash"
root:x:0:0:root:/root:/bin/bash
imooc:x:502:889:kk,kk,kk,kk:/home/xxx:/bin/bash
cls:x:500:889:dgdzmx:/home/cls:/bin/bash
user1:x:503:503::/home/user1:/bin/bash
tony:x:504:504::/home/tony:/bin/bash
lw:x:505:505::/home/lw:/bin/bash
user2:x:506:506::/home/user2:/bin/bash
[root@localhost home]# cat /etc/passwd |grep "/bin/bash" | awk 'BEGIN{FS=":"}{printf $1 "\t" $3}'
root    0imooc  502cls  500user1    503tony 504lw   505user2    506[root@localhost home]# cat /etc/passwd |grep "/bin/bash" | awk 'BEGIN{FS=":"}{printf $1 "\t" $3 "\n"}'
root    0
imooc   502
cls 500
user1   503
tony    504
lw  505
user2   506
[root@localhost home]# cat /etc/passwd |grep "/bin/bash" |grep -v "root" |  awk 'BEGIN{FS=":"}{printf $1 "\t" $3 "\n"}'
imooc   502
cls 500
user1   503
tony    504
lw  505
user2   506
[root@localhost home]# 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值