编辑
2019-12-24
编程
00

目录

awk
1. 语法构造
2. 语法
2.1 基本语法
2.1.1 AWK 命令行
2.2.1 -v 变量赋值选项
2.2.5 --profile[=file]选项
2.2.7 --version 选项
2.3.1 标准 AWK 变量(一)
2.3.1.1 ARGC 命令行参数个数
2.3.1.2 ARGV 命令行参数数组
2.3.1.3 CONVFMT 数字的约定格式
2.3.1.4 ENVIRON 环境变量
2.3.1.5 FILENAME 当前文件名
2.3.1.6 FS 输入字段的分隔符
2.3.1.7 NF 字段数目
2.3.1.8 NR 行号
2.3.1.9 FNR 行号(相对当前文件)
2.3.1.10 OFMT 输出格式数字
2.3.1.11 OFS 输出字段分隔符
2.3.1.12 ORS 输出行分隔符
2.3.1.13 RLENGTH
2.3.1.14 RS 输入记录分隔符
2.3.1.15 RSTART
2.3.1.16 SUBSEP 数组子脚本的分隔符
2.3.2 标准 AWK 变量(二)
2.3.3 GNU AWK的变量
2.3.3.1 ARGIND
2.3.3.2 BINMODE
2.3.3.3 ERRORNO
2.3.3.4 FIELDWIDTHS
2.3.3.5 IGNORECASE
2.3.3.6 LINT
2.3.3.7 PROCINFO
2.3.3.8 TEXTDOMAIN
2.4 操作符
2.4.1 计算
2.4.2 增减运算符
2.4.3 赋值操作符
2.4.4 关系操作符
2.4.5 逻辑操作符
2.4.6 三元操作符
2.4.7 一元操作符
2.4.8 指数操作符
2.4.9 字符串连接操作符
2.4.10 数组成员操作符
2.4.11 正则表达式操作符
2.5 数组
2.5.1 创建
2.5.2 删除
2.6 流程控制
2.7 循环
2.8 函数
2.8.1 内置函数
2.8.2 自定义函数
2.9 管道
2.10 执行shell命令
2.10.1 使用system函数
3. 使用示例

awk

1. 语法构造

BEGIN {awk-commands} {awk-commands} END {awk-commands}

  • BDGIN 语句块: BEGIN {awk-commands}
    • 初始化变量,只执行一次
    • BEGIN 关键字,必须大写
    • 可选的(非必须的)
  • BODY语句块: {awk-commands}
    • 每一行输入执行一次
    • 没有关键字
    • 通过模式来控制
  • END语句块: END {awk-commands}
    • 程序最后执行
    • END 关键字,必须为大写
    • 可选的

2. 语法

2.1 基本语法

2.1.1 AWK 命令行

  • 使用单引号在命令行中指定 AWK 命令

    bash
    awk [options] file ...
  • 例子

    bash
    $ awk '{print}' marks.txt

2.1.2 AWK程序文件

  • 使用脚本文件提供AWK命令

    bash
    awk [options] -f file ....
  • 例子

    • 创建一个 command.awk 文件

      bash
      {print}
    • 执行命令(效果与 2.1.1 中例子一致)

      bash
      $ awk -f command.awk marks.txt

2.2 标准选项

2.2.1 -v 变量赋值选项

  • 命令

    bash
    -v var=val --assign var=val

    将一个值赋予一个变量,它会在程序开始之前进行赋值

  • 例子

    bash
    $ awk -v name=Test 'BEGIN{printf "Name = %s\n", name}' Name = Test

2.2.2 --dump-variables[=file] 选项

  • 命令

    bash
    -d[file] --dump-variables[=file]

    输出排好序的全局变量列表和它们最终的值到文件中,默认的文件是 awkvars.out

  • 例子

    bash
    [root@rcmaster ~]# awk -dtemp.out '' [root@rcmaster ~]# cat temp.out ARGC: 1 ARGIND: 0 ARGV: array, 1 elements BINMODE: 0 CONVFMT: "%.6g" ERRNO: "" FIELDWIDTHS: "" FILENAME: "" FNR: 0 FPAT: "[^[:space:]]+" FS: " " IGNORECASE: 0 LINT: 0 NF: 0 NR: 0 OFMT: "%.6g" OFS: " " ORS: "\n" RLENGTH: 0 RS: "\n" RSTART: 0 RT: "" SUBSEP: "\034" TEXTDOMAIN: "messages"

2.2.3 --lint[=fatal] 选项

  • 该选项允许检查程序的不兼容性或者模棱两可的代码,当提供参数 fatal的时候,它会对待Warning消息作为Error。

  • 命令

    bash
    -L [value] --lint[=value]

    检查程序的不兼容性或者模棱两可的代码,当提供参数 fatal 的时候,它会对待Warning消息作为Error。

  • 例子

    bash
    $ awk --lint '' /bin/ls awk: cmd. line:1: warning: empty program text on command line awk: cmd. line:1: warning: source file does not end in newline awk: warning: no program text at all!

2.2.4 --posix 选项

  • 命令

    bash
    -P --posix

    该选项开启严格的POSIX兼容。

2.2.5 --profile[=file]选项

  • 命令

    bash
    -p[prof_file] --profile[=prof_file]

    该选项会输出一份格式化之后的程序到文件中,默认文件是 awkprof.out

  • 例子

    bash
    $ awk --profile 'BEGIN{printf"---|Header|--\n"} {print} END{printf"---|Footer|---\n"}' marks.txt > /dev/null $ cat awkprof.out # gawk 配置, 创建 Wed Oct 26 15:05:49 2016 # BEGIN 块 BEGIN { printf "---|Header|--\n" } # 规则 { print $0 } # END 块 END { printf "---|Footer|---\n" }

2.2.6 --traditional 选项

  • 命令

    bash
    -c --traditional

    禁止所有的gawk规范的扩展。

2.2.7 --version 选项

  • 命令

    bash
    -V --version

    输出版本号

  • 例子

    bash
    [root@rcmaster ~]# awk -V GNU Awk 4.0.2 Copyright (C) 1989, 1991-2012 Free Software Foundation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

2.3 内建变量

2.3.1 标准 AWK 变量(一)

2.3.1.1 ARGC 命令行参数个数
bash
[root@rcmaster ~]# awk 'BEGIN {print "Arguments =", ARGC}' a b c d Arguments = 5
2.3.1.2 ARGV 命令行参数数组
bash
[root@rcmaster ~]# awk 'BEGIN { > for(i=0;i<ARGC-1;++i){ > printf "ARGV[%d]=%s\n", i, ARGV[i] > } > }' a b c d ARGV[0]=awk ARGV[1]=a ARGV[2]=b ARGV[3]=c
  • 索引范围从0 - ARGC - 1
2.3.1.3 CONVFMT 数字的约定格式
bash
$ awk 'BEGIN { print "Conversion Format =", CONVFMT }' Conversion Format = %.6g
  • 默认值是**%.6g**
2.3.1.4 ENVIRON 环境变量
bash
[root@admin109 ~]# awk 'BEGIN {print ENVIRON["JAVA_HOME"]}' /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.232.b09-0.el7_7.x86_64
2.3.1.5 FILENAME 当前文件名
[root@admin109 ~]# awk 'END {print FILENAME}' anaconda-ks.cfg anaconda-ks.cfg
  • END 中使用
2.3.1.6 FS 输入字段的分隔符

代表了输入字段的分隔符,默认值为空格,可以通过-F选项在命令行选项中修改它。

bash
$ awk 'BEGIN {print "FS = " FS}' | cat -vte FS = $ $ awk -F , 'BEGIN {print "FS = " FS}' | cat -vte FS = ,$
2.3.1.7 NF 字段数目

代表了当前行中的字段数目,例如下面例子打印出了包含大于两个字段的行

bash
$ echo -e "One Two\nOne Two Three\nOne Two Three Four" | awk 'NF > 2' One Two Three One Two Three Four
2.3.1.8 NR 行号
bash
$ echo -e "One Two\nOne Two Three\nOne Two Three Four" | awk 'NR < 3' One Two One Two Three
2.3.1.9 FNR 行号(相对当前文件)

与NR相似,不过在处理多文件时更有用,获取的行号相对于当前文件。

2.3.1.10 OFMT 输出格式数字

默认值为**%.6g**

bash
$ awk 'BEGIN {print "OFMT = " OFMT}' OFMT = %.6g
2.3.1.11 OFS 输出字段分隔符

输出字段分隔符,默认为空格

bash
$ awk 'BEGIN {print "OFS = " OFS}' | cat -vte OFS = $
2.3.1.12 ORS 输出行分隔符

默认值为换行符

bash
$ awk 'BEGIN {print "ORS = " ORS}' | cat -vte ORS = $ $
2.3.1.13 RLENGTH

代表了 match 函数匹配的字符串长度。

bash
$ awk 'BEGIN { if (match("One Two Three", "re")) { print RLENGTH } }' 2
2.3.1.14 RS 输入记录分隔符
bash
$ awk 'BEGIN {print "RS = " RS}' | cat -vte RS = $ $
2.3.1.15 RSTART

match函数匹配的第一次出现位置

bash
$ awk 'BEGIN { if (match("One Two Three", "Thre")) { print RSTART } } 9
2.3.1.16 SUBSEP 数组子脚本的分隔符

数组子脚本的分隔符,默认为**\034**

bash
$ awk 'BEGIN { print "SUBSEP = " SUBSEP }' | cat -vte SUBSEP = ^\$

2.3.2 标准 AWK 变量(二)

  • $ 0 代表了当前行

  • $n 当前行中的第n个字段

bash
[root@rcmaster ~]# cat awk.test.txt line1 value 5 line2 value 10 line3 value 15 line4 value 20
bash
[root@rcmaster ~]# awk '{print $0, "|", $1, "|", $2}' awk.test.txt line1 value 5 | line1 | value line2 value 10 | line2 | value line3 value 15 | line3 | value line4 value 20 | line4 | value

2.3.3 GNU AWK的变量

2.3.3.1 ARGIND

当前被处理的ARGV的索引

bash
$ awk '{ print "ARGIND = ", ARGIND; print "Filename = ", ARGV[ARGIND] }' junk1 junk2 junk3 ARGIND = 1 Filename = junk1 ARGIND = 2 Filename = junk2 ARGIND = 3 Filename = junk3
2.3.3.2 BINMODE

在非POSIX系统上指定对所有的文件I/O采用二进制模式。

2.3.3.3 ERRORNO

一个代表了getline跳转失败或者是close调用失败的错误的字符串。

bash
$ awk 'BEGIN { ret = getline < "junk.txt"; if (ret == -1) print "Error:", ERRNO }' Error: No such file or directory
2.3.3.4 FIELDWIDTHS

设置了空格分隔的字段宽度变量列表的话,GAWK会将输入解析为固定宽度的字段,而不是使用FS进行分隔。

2.3.3.5 IGNORECASE

设置了这个变量的话,AWK会忽略大小写。

bash
$ awk 'BEGIN{IGNORECASE = 1} /amit/' marks.txt 1) Amit Physics 80
2.3.3.6 LINT

提供了对**--lint**选项的动态控制。

bash
$ awk 'BEGIN {LINT = 1; a}' awk: cmd. line:1: warning: reference to uninitialized variable `a' awk: cmd. line:1: warning: statement has no effect
2.3.3.7 PROCINFO

包含进程信息的关联数组,例如UID,进程ID等

bash
$ awk 'BEGIN { print PROCINFO["pid"] }' 4316
2.3.3.8 TEXTDOMAIN

代表了AWK的文本域,用于查找字符串的本地化翻译。

bash
$ awk 'BEGIN { print TEXTDOMAIN }' messages

2.4 操作符

2.4.1 计算

+-*/%

2.4.2 增减运算符

自增自减

++i, i++, --i, i--

2.4.3 赋值操作符

=

2.4.4 关系操作符

==

<

<=

>

>=

!=

2.4.5 逻辑操作符

&&

||

!

2.4.6 三元操作符

express ? [express1|value1] : [express2|value2]

2.4.7 一元操作符

=-

=+

2.4.8 指数操作符

t^num

2.4.9 字符串连接操作符

$ awk 'BEGIN { str1 = "Hello, "; str2 = "World"; str3 = str1 str2; print str3 }' Hello, World

2.4.10 数组成员操作符

arra[index]

2.4.11 正则表达式操作符

正则表达式操作符使用 ~!~ 分别代表匹配和不匹配。

$ awk '$0 ~ 9' marks.txt 2) Rahul Maths 90 5) Hari History 89 $ awk '$0 !~ 9' marks.txt 1) Amit Physics 80 3) Shyam Biology 87 4) Kedar English 85 # 匹配正则表达式需要在表达式前后添加反斜线,与js类似吧 $ tail -n 40 /var/log/nginx/access.log | awk '$0 ~ /ip\[127\.0\.0\.1\]/'

2.5 数组

2.5.1 创建

arrayName[index] = value

不仅可以使用数字索引的数组,还可以使用字符串作为索引

2.5.2 删除

delete arrayName[index]

2.6 流程控制

if(condition){

​ action

} else if(condition){

​ action

} else{

​ action

}

2.7 循环

循环操作与其他C系语言一样,主要包括 forwhiledo...whilebreakcontinue 语句,当然,还有一个 exit语句用于退出脚本执行。

for (initialisation; condition; increment/decrement) action while (condition) action do action while (condition)

2.8 函数

2.8.1 内置函数

2.8.2 自定义函数

bash
function function_name(argument1, argument2, ...) { function body }

2.9 管道

与 linux 命令一致

2.10 执行shell命令

在AWK中执行shell命令有两种方式

  • 使用system函数
  • 使用管道

2.10.1 使用system函数

system函数用于执行操作系统命令并且返回命令的退出码到awk。

bash
END { system("date | mail -s 'awk run done' root") }

3. 使用示例

bash
[root@rcmaster ~]# ps -ef|grep Short|grep -v grep|awk 'BEGIN {printf "pid\n"}{print $2}' pid 9444 [root@rcmaster ~]# ps -ef|grep Short|grep -v grep|kill -9 `awk '{print $2}'`

本文作者:Yui_HTT

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.14.8