AWK工具学习(一)-awk介绍

任何awk语句都由模式和动作组成,模式驱动动作触发事件,动作执行对输入行的处理
awk支持'?'、'+'两个扩展元字符,而grep和sed并不支持
A.1 举个小例子,演示awk的使用(以下是全部的操作过程)

[lidc@hd66 awk-experiment]$ touch input
[lidc@hd66 awk-experiment]$ awk '/^$/{print "this is a blank line"}' input
[lidc@hd66 awk-experiment]$ cat input
1.[lidc@hd66 awk-experiment]$ echo '' > input
[lidc@hd66 awk-experiment]$ cat input

2.[lidc@hd66 awk-experiment]$ awk '/^$/{print "this is a blank line"}' input
this is a blank line
3.[lidc@hd66 awk-experiment]$ echo 'test by tony' >input
[lidc@hd66 awk-experiment]$ cat input
test by tony
4.[lidc@hd66 awk-experiment]$ awk '/^$/{print "this is a blank line"}' input
[lidc@hd66 awk-experiment]$

解释:以上是判断输入文件是不是空行的一个例子,1处输入为空,所以执行2后输出'this is a blank line'
3处输入了非空数据,所以在执行4的时候未输出

另外命令行模式下,如果没有指定输入文件将从命令行读取相关文本

[lidc@hd66 awk-experiment]$ awk '/^$/{print "this is a blank line"}'

this is a blank line

this is a blank line

this is a blank line

A.2 awk编程模型
awk程序由一个主输入循环维持,主循环依次读取文件行,程序员只需要对行进行操作,打开文件、关闭文件的操作都由主循环管理

awk还定义了两个特殊的字段:BEGIN和END。BEGIN用于在未读取文件行之前执行。上例子:

[lidc@hd66 awk-experiment]$ awk 'BEGIN{print "joke"} /^$/{print "this is a blank line"}END{print "the end"}' input
joke
this is a blank line
the end
[lidc@hd66 awk-experiment]$ cat input
test by tony

[lidc@hd66 awk-experiment]$

A.3 调用方法
简单说:
1. 命令行执行
awk [-F 域分隔符] 'awk程序段' 输入文件
hdfs cat /user/ddclick/visitpath-v2_2013-02-18/step_dict/part-* | awk -F~==~ '{print $1}' > urls

2.使用-f调用
awk -f awk脚本文件 输入文件

3.设置脚本为可执行,然后直接执行
./awk脚本文件 输入文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值