我有这个......
#!/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文本。不知道最好的方法是如何做到这一点。
答案 0 :(得分:3)
尝试:
$ 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 -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
。
创建此脚本文件:
$ 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.
$ 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.
创建此文件:
$ 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.