一、awk基本用法
1.awk命令解析
awk工具概述
awk编程语音/数据处理引擎
---创造者:Aho、Weinberger、Kernighan
---基于模式匹配检查输入文本,逐行处理并输出
---通常用在Shell脚本中,获取指定的数据
---单独用时,可对文本数据做统计
2.命令格式解析
主要用法
----格式1:前置命令 | awk [选项] '[条件]{指令}'
----格式2:awk [选项] '[条件]{指令}' 文件....
常用命令选项
-F : 指定分隔符,可省略(默认空格或tab)
- 检查登录失败的IP地址有那些
- 检查内存的剩余容量
- 过滤网络流量
常用指令
- print :输出
[root@server0 ~]# cat test.txt #创建素材
hello the world
welcome to beijing
[root@server0 ~]# awk '{print}' test.txt #输出所有行
hello the world
welcome to beijing
[root@server0 ~]# awk '{print$1}' test.txt #输出所有行的第一列
hello
welcome
[root@server0 ~]# awk '{print $2}' test.txt #输出所有行的第二列
the
to
[root@server0 ~]# awk '{print $2,$1}' test.txt #输出所有行的第2 1 列
the hello
to welcome
[root@server0 ~]# awk '{print $3,$1}' test.txt #输出所有行的第3 1列
world hello
beijing welcome
[root@server0 ~]# awk '{print$0}' test.txt #输出所有行所有列
hello the world
welcome to beijing
[root@server0 ~]# awk '{print$3,$0}' test.txt #输出所有行的第3列 所有列
world hello the world
beijing welcome to beijing
[root@server0 ~]# awk -F: '{print $1}' user #定义:作为分隔符,然后输出第1列
root
bin
daemon
adm
lp
[root@server0 ~]# awk -F[:/] '{print $1}' user #定义:或者/作为分隔符
root
bin
daemon
adm
lp
awk内置变量
- 有特殊含义,可以直接使用
变量 | 用途 |
FS | 保存或设置字段分隔符,如FS=":",与-F功能一样 |
$n | 指定分隔符的第n个字段,如$1.$3分别表示第1.第3列 |
$0 | 当前读入的整行文本内容 |
NF | 记录当前处理的字段个数(列数) |
NR | 记录当前已读入行的数量(行数) |
ifconfig eth0 | awk '/RX p/{print $4,$5}' 找到网卡信息中的接收流量
ifconfi