linux - 在 AWK 中使用 2 个关键字开始和停止打印

标签 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 文本。不确定执行此操作的最佳方法是什么。

最佳答案

使用 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 命令制作成脚本

方法一

创建这个脚本文件:

$ 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.

方法二

创建这个文件:

$ 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.

关于linux - 在 AWK 中使用 2 个关键字开始和停止打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40370155/

相关文章:

linux - 我可以在 Ubuntu 上开发 Microsoft Dynamics 365 吗?

linux - 一起使用 linux 命令 "sort -f | uniq -i"忽略大小写

linux - 使用 awk 或 sed 对以模式开头的行进行排序

bash - Awk:将输出格式化为 json

regex - 使用 sed 和 regex 更改 bash 中不包括变量的每个符号

linux - 如何在Linux中安装工具链

c++ - linux 中可执行文件的主管

python - Linux 中的安全 Python 环境

linux - 求列中字段的平均值

linux - 如何使用 Linux/Unix 实用程序提取每个输入行开头的整数或小数?