课时10 awk文本处理工具
一、关于文本处理
Shell输出为文本:面向过程,而非面向对象。
非交互式处理方式:
重定向、管道、命令替换
head、more、cut、tr
grep、awk、sed
awk编程语言/数据处理引擎
创造者:Aho、Weinberger、Kernighan
基于
模式匹配检查输入
将期望的匹配结果
print到屏幕
注:awk不能改变原有文本中的内容。
二、awk基本命令格式
语法格式:
awk '模式 {操作}
' 文件1 文件2 ......
例如: awk 'NR=1 {print}' /etc/hosts
常用的内建变量:
NR
|
当前处理行的序数(行号)
|
FS
|
字段分割,缺省为空格或Tab
|
$n
|
当前行的第n个字段
|
$0
|
当前行的所有文本内容
|
三、常见用法示例
准备测试文件:file.txt
[
root@localhost ~]# cat file.txt
1 This is the first line.
2 Hello, Everybody!
3 192.168.4.2 w2k8.benet.com
4 hunter:x:504:504::/home/hunter:/bin/bash
示例1:按行号输出文本
[
root@localhost ~]#
awk 'NR==1,NR==3 {print}' file.txt //输出第一行至第三行
1 This is the first line.
2 Hello, Everybody!
3 192.168.4.2 w2k8.benet.com
1 This is the first line.
3 192.168.4.2 w2k8.benet.com
1 This is the first line.
3 192.168.4.2 w2k8.benet.com
1 This is the first line.
3 192.168.4.2 w2k8.benet.com
示例2:使用正则表达式
2 Hello, Everybody!
3 192.168.4.2 w2k8.benet.com
4 hunter:x:504:504::/home/hunter:/bin/bash
示例3:指定分隔、指定输出字段
2 Everybody!
3 w2k8.benet.com
3 192.168.4.2 w2k8.benet.com