我有一个输入文本文件,其中包含由 3 个空行分隔的段落。示例:
P1
P1
empty line here
empty line here
empty line here
P2
P2
empty line here
empty line here
empty line here
P3
P3
empty line here
empty line here
empty line here
目前,我正在使用写入 *.awk 文件的代码来获取段落:
BEGIN{ORS=RS="\n\n\n"}
/some text pattern comes here because I dont want to print every paragraph just some of them but in reversed order/
所以我希望输出文件如下所示:
P3
P3
empty line here
empty line here
empty line here
P2
P2
empty line here
empty line here
empty line here
P1
P1
empty line here
empty line here
empty line here
所以我想知道是否可以将每个段落打印到输出文件的顶部以获得相反的顺序。可以做到吗?
最佳答案
如果设置 RS=""
那么 awk 将分隔 multi-line records用空行分隔。
给定:
$ cat /tmp/so.txt
P1
P1
P2
P2
P3
P3
然后,您可以获取每条记录的 $0
,然后反转该记录:
$ awk 'BEGIN{RS=""} {a[i++]=$0} END {while(i--){ print a[i]; print "\n\n\n"}}' /tmp/so.txt
P3
P3
P2
P2
P1
P1
如果您有固定的三空白行分隔符(并且您有 gawk
),您也可以这样做:
$ awk 'BEGIN{RS="\n\n\n"} {a[i++]=$0} END {while(i--) print a[i]}' /tmp/so.txt
根据评论进行编辑
给定:
P1 a
P1 b
P2 a filter this block
P2 b
P3 a
P3 b
您可以添加模式来过滤不需要的 block :
$ awk 'BEGIN{RS=""} /filter/ {next} {a[i++]=$0} END {while(i--){ print a[i]; print "\n"}}' /tmp/so.txt
P3 a
P3 b
P1 a
P1 b
关于awk 打印到输出文件的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34712012/