awk命令的使用

awk命令的使用

awk命令格式
awk '条件1{动作1} 条件2{动作2}…' 文件名

在介绍awk命令的用法前,先来看一下cut命令,对比一下就能体现出awk命令的强大。

[root@localhost~]#vim student.txt
[root@localhost~]#cat student.txt 
ID    Name      PHP   Linux   MySQL   Average
1     Jaking    82     95     86       87.66
2     Geling    74     96     87       85.66
3     igi       99     83     93       91.66
[root@localhost~]#cut -d " " -f 1 student.txt 
ID
1
2
3
[root@localhost~]#cut -d " " -f 2 student.txt 




[root@localhost~]#cut -d " " -f 4 student.txt 




[root@localhost~]#

很明显,后面两条命令执行后截取不到任何内容。这是因为当用空格作为分隔符时,有用信息列与列之间有一些空格,这样一来cut命令很可能就会截取到空格所在的列。

awk就不一样了,它可以准确截取到有用信息。

[root@localhost~]#awk '{printf $2 "\t" $6 "\n"}' student.txt
Name    Average
Jaking  87.66
Geling  85.66
igi     91.66

[root@localhost~]#df -h
Filesystem                    Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root   18G  7.1G  9.4G  43% /
tmpfs                         2.0G  224K  2.0G   1% /dev/shm
/dev/sda1                     485M   40M  421M   9% /boot
[root@localhost~]#df -h | awk '{print $1 "\t" $3}'
Filesystem  Used
/dev/mapper/VolGroup-lv_root    7.1G
tmpfs   224K
/dev/sda1   40M

#注意:如果用printf打印内容到屏幕,则需要在最后加\n换行。

awk的BEGIN与END模式

这两种模式的作用是在awk命令执行前和执行后做一些动作。

[root@localhost~]#awk 'BEGIN{printf "This is a transcript \n" } {printf $2 "\t" $6 "\n"}' student.txt
This is a transcript 
Name    Average
Jaking  87.66
Geling  85.66
igi 91.66
[root@localhost~]#awk '{printf $2 "\t" $6 "\n"}' student.txt
Name    Average
Jaking  87.66
Geling  85.66
igi 91.66
[root@localhost~]#awk 'END{printf "The End \n" } {printf $2 "\t" $6 "\n"}' student.txt
Name    Average
Jaking  87.66
Geling  85.66
igi 91.66
The End 
[root@localhost~]#awk '{printf $2 "\t" $6 "\n"}' student.txt
Name    Average
Jaking  87.66
Geling  85.66
igi 91.66

FS内置变量

FS变量的作用是设置分隔符,一般要结合BEGIN一起使用。

[root@localhost~]#cat /etc/passwd | grep "/bin/bash" | awk '{FS=":"} {printf $1 "\t" $3 "\n"}' #以":"为分隔符截取/etc/passwd文件里与/bin/bash有关的行。
root:x:0:0:root:/root:/bin/bash #第一行没有被截取是因为awk是先读取文件的第一行,然后再进行截取的。为了把第一行也截取,可以加上BEGEN。
mysql   27
[root@localhost~]#cat /etc/passwd | grep "/bin/bash" | awk 'BEGIN {FS=":"} {printf $1 "\t" $3 "\n"}'
root    0
mysql   27

关系运算符

[root@localhost~]#cat student.txt 
ID    Name      PHP   Linux   MySQL   Average
1     Jaking    82     95     86       87.66
2     Geling    74     96     87       85.66
3     igi       99     83     93       91.66
[root@localhost~]#cat student.txt | grep -v Name | awk '$6 >= 87 {printf $2 "\n" }'  #加入数学关系式,截取平均分大于等于87分的人名。
Jaking
igi

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。