使用AWK

时间:2016-11-01 23:24:21

标签: linux awk

我有这个......

#!/usr/bin/awk -f
{if($1 == "#BEGIN") while($1 != "#END") print}

当读入输入文件时,我想要输出的内容是这个。

This is a simple test file.
#BEGIN
These lines should be extracted by our script.

Everything here will be copied.
#END
That should be all.
#BEGIN
Nothing from here.
#END
user$ extract.awk test1.txt
These lines should be extracted by our script.

Everything here will be copied.
user$

仅复制第一组BEGIN和END文本。不知道最好的方法是如何做到这一点。

1 个答案:

答案 0 :(得分:3)

使用awk

尝试:

$ awk 'f && /^#END/{exit} f{print} /^#BEGIN/{f=1}' test1.txt
These lines should be extracted by our script.

Everything here will be copied.

工作原理:

  • f && /^#END/{exit}

    如果f非零并且此行以#END开头,请退出。

  • f{print}

    如果变量f非零,请打印此行。

  • /^#BEGIN/{f=1}

    如果此行以#BEGIN开头,请将变量f设置为1。

使用sed

$ sed -n '/^#BEGIN/{n; :a; /^#END/q; p; n; ba}' test1.txt 
These lines should be extracted by our script.

Everything here will be copied.

工作原理:

  • /^#BEGIN/{...}

    当我们到达以#BEGIN开头的行时,执行花括号中的命令。这些命令是:

  • n

    请阅读下一行。

  • :a

    定义标签a

  • /^#END/q

    如果当前行以#END开头,则退出。

  • p

    打印此行。

  • n

    请阅读下一行。

  • ba

    分支(跳转)回到标签a

将awk命令转换为脚本

方法1

创建此脚本文件:

$ cat script1
#!/bin/sh
awk 'f && /^#END/{exit} f{print} /^#BEGIN/{f=1}' "$1"  

这可以执行:

$ bash script1 test1.txt 
These lines should be extracted by our script.

Everything here will be copied.

方法2

创建此文件:

$ cat script.awk
#!/usr/bin/awk -f
f && /^#END/{exit}
f{print}
/^#BEGIN/{f=1}

按如下方式运行:

$ awk -f script.awk test1.txt 
These lines should be extracted by our script.

Everything here will be copied.

或者,让它可执行:

$ chmod +x script.awk

执行它:

$ ./script.awk test1.txt
These lines should be extracted by our script.

Everything here will be copied.

将awk脚本变为shell函数

$ extract() { awk 'f && /^#END/{exit} f{print} /^#BEGIN/{f=1}' "$1"; }
$ extract test1.txt 
These lines should be extracted by our script.

Everything here will be copied.

将sed命令转换为脚本

创建此文件:

$ cat script.sed
#!/bin/sed -nf
/^#BEGIN/{n; :a; /^#END/q; p; n; ba}

使其可执行:

$ chmod +x script.sed

然后,运行它:

$ ./script.sed test1.txt
These lines should be extracted by our script.

Everything here will be copied.