我有这个...
#!/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/