文本分析工具awk

版权声明:未经允许不得转载。 https://blog.csdn.net/qq_35958788/article/details/82941818

简述

  • grep, sed 与 awk并称linux三剑客,grep查找sed编辑,awk根据内容分析并处理。
  • 使用方法:
    awk '{pattern + action}' {filenames}
    其中 pattern 表示 AWK 在数据中查找的内容,而 action 是在找到匹配内容时所执行的一系列命令。花括号({})不需要在程序中始终出现,但它们用于根据特定的模式对一系列指令进行分组。 pattern就是要表示的正则表达式,用斜杠括起来。
    通常,awk是以文件的一行为处理单位的。awk每接收文件的一行,然后执行相应的命令,来处理文本。

语法

常用变量

  • NF: 每一行处理的字段数
  • NR 目前处理到第几行
  • FS 目前的分隔符

逻辑判断

>
< 
>= 
<= 
== 
!=
=

举例说明

文档原文

You say that you love rain,

but you open your umbrella when it rains...

You say that you love the sun,

but you find a shadow spot when the sun shines...

You say that you love the wind,

But you close your windows when wind blows...

This is why I am afraid;

You say that you love me too...

输出指定列

  • 输出第一列($0 代表整行 $1代表第一个区域, 依此类推)
tail -n 3 poetry | awk '{print $1}'
//结果
This

You
  • 连接多列拼接(\t分隔符,两边的空格可以省略)
tail -n 3 poetry | awk '{print $1 "\t" $3}'
//结果
This	why

You	that
  • 例3(首先定义分隔符为:;然后判断,不需要写到括号,然后执行动作)
cat /etc/passwd | awk '{FS=":"} $3<10 {print $1 "\t" $3}' 
  • 例4(将带有特定字符的行打印出来)
awk '/your/ {print NR}' poetry
//结果
3
11

https://www.cnblogs.com/moveofgod/p/3540575.html
https://blog.oldboyedu.com/swordsman-sed/

猜你喜欢

转载自blog.csdn.net/qq_35958788/article/details/82941818