awk学习笔记
1.awk
参考:Linux awk 命令 | 菜鸟教程 (runoob.com)
https://tianchi.aliyun.com/forum/post/33368
awk脚本基本格式***
awk 'BEGIN{commands} pattern{commands} END{commands}' file
awk是以行为单位的,在大段文本输入时,是一行一行读入;
awk无论行还是列都是从1开始的,比如
ifconfig eth0 | awk '{print $1}' // 输出的是由‘ ’分割的一列列,并输出第一列结果
一些特殊的内建变量(重点几个)
变量 | 描述 |
---|---|
$n | 当前记录(一行)第n个字段(列) |
NF | 当前一行被FS分割,产生了多少列(从1开始) |
NR | 当前行号(从1开始) |
FNR | 各文件分别计数的行号 |
awk中使用正则表达式(模式)
有几种方式使用模式
1.在左引号后直接使用模式
ifconfig eth0 | awk '/ether/' // 直接输出存在ether的所有行
//中是模式
2.更加具体的定位使用模式,如需要第一列中存在ether才进行显示
ifconfig eth0 | awk '$1 ~ /ether/'
这里用到了 ~ 表示模式的开始
3.模式取反,我不想要包含某个字段的行数据
ifconfig eth0 | awk '!/ether/'
ifconfig eth0 | awk '$1 !~ /ether/'
上述的简单学习,就可以使用awk定位出eth0网卡的IP地址、mac地址等信息了
ifconfig eth0 | awk '/ether/ {print $2}' // 获取mac地址
ifconfig eth0 | awk '$1=="inet" {print $2}' // 获取IPv4地址
ifconfig eth0 | awk '/inet6/ {print $2}' // 获取IPv6地址