【Shell】【学习笔记】Linux Shell脚本应用(十)

课时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
[ root@localhost ~]# awk ' (NR==1) || (NR==3) {print}' file.txt    // 输出 第一行和第三行
1 This is the first line.
3 192.168.4.2 w2k8.benet.com
[ root@localhost ~]# awk ' (NR%2==1) {print}' file.txt    // 输出 奇数行
1 This is the first line.
3 192.168.4.2 w2k8.benet.com
[ root@localhost ~]# awk ' (NR%2==0) {print}' file.txt    // 输出偶数行
1 This is the first line.
3 192.168.4.2 w2k8.benet.com

示例2:使用正则表达式
[ root@localhost ~]# awk ' /2/ {print}' file.txt      //输出包含2的行
2 Hello, Everybody!
3 192.168.4.2 w2k8.benet.com
[ root@localhost ~]# awk ' /bash$/ {print}' file.txt      //输出以bash字符串结尾的行
4 hunter:x:504:504::/home/hunter:/bin/bash

示例3:指定分隔、指定输出字段
[ root@localhost ~]# awk ' NR==2,NR==3 {print $1,$3}' file.txt      //输出第二行至第三行的第一和第三个字段
2 Everybody!
3 w2k8.benet.com
[ root@localhost ~]# awk  -F. ' $5=="benet" {print  $0}' file.txt      //以.为分隔符,输出第五个字段为benet的行
3 192.168.4.2 w2k8.benet.com

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值