awk命令学习

据说有人用这个装逼。哈哈。我只求掌握基本。

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

条件(Pattern):

-一般使用关系表达式作为条件

-可以使用函数等

动作(Action):

-格式化输出

-流程控制语句

测试文档:

 

1.输出第2,4行

[root@myfuture ~]# awk '{print $2 "\t" $4 }' student.txt 
Name    Mark
furong    85
fengj    60
cang    70

2.输出df -h 的第1,3行

[root@myfuture ~]# df -h | awk '{print $1 "\t" $3}'
Filesystem    Used
/dev/mapper/vg_myfuture-lv_root    
18G    13G
tmpfs    228K
/dev/sda1    29M
/dev/sr0    4.4G

而cut却无法实现

[root@myfuture ~]# df -h | cut -f 1,3
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg_myfuture-lv_root
                       18G  3.7G   13G  23% /
tmpfs                 491M  228K  491M   1% /dev/shm
/dev/sda1             477M   29M  424M   7% /boot
/dev/sr0              4.4G  4.4G     0 100% /media/CentOS_6.6_Final

3.获取/dev/sda1的使用情况:

[root@myfuture ~]# df -h | grep "/dev/sda1" | awk '{print $5}' | cut -d "%" -f 1
7

4.BEGIN关系表达式,只有先满足关系表达式后,才能继续动作。

[root@myfuture ~]# awk 'BEGIN{print "this is a test"}{print $2 "\t" $4}' student.txt 
this is a test
Name    Mark
furong    85
fengj    60
cang    70

5.END会在所有的输入都被处理完后进行匹配。

[root@myfuture ~]# awk 'END{print "this is a test"}{print $2 "\t" $4}' student.txt 
Name    Mark
furong    85
fengj    60
cang    70
this is a test

6.提取用户名与ID

[root@myfuture ~]# cat /etc/passwd | grep /bin/bash | awk 'BEGIN{FS=":"}{print $1 "\t" $3}'
root    0
zabbix    500
hadoop    501
user1    502

7.提取分数大于70的人名

[root@myfuture ~]# cat student.txt | grep -v Name | awk '$4>=70 {print $2}'
furong
cang

8.awk默认以空格为分隔符,需用awk中的'-F'标志指定你的分隔符

[root@myfuture ~]#  echo 'one mississippi,two mississippi,three mississippi,four mississippi' | awk -F , '{print $4}' 
four mississippi

9.只要最后字段。 awk中内置的$NF变量代表字段的数量,这样你就可以用它来抓取最后一个元素:

echo 'one two three four' | awk '{print $NF}' 

倒数第二个字段:

[root@myfuture ~]# cat student.txt | awk '{print $(NF-1)}'
gender
F
F
F

中间字段:

[root@myfuture ~]# cat student.txt | awk '{print $((NF/2)+1)}'
gender
F
F
F

10.awk的跨行状态

[root@myfuture ~]# echo -e 'one 1\ntwo 2' | awk '{sum+=$2} END {print sum}'
3

 

转载于:https://www.cnblogs.com/XYJK1002/p/5329782.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值