我们如何用 awk 做到这一点?
输入文件
Line 1
Line 2
####PATTERN####### (Line 3)
Line 4
Line 5
Line 6
####PATTERN####### (line 7)
Line 8
####PATTERN####### (Line 9)
ETC..
输出文件
Line 1
Line 3
Line 4
Line 5
Line 7
Line 9
sed '$!N;s/.*####PATTERN####### \(.*\)/\1/;P;D' text
Line 1
(Line 3)
Line 4
Line 5
(line 7)
(Line 9)
The N
command grabs the next line from the input into the pattern space so that we can perform a pattern matching against two lines. If we discover ####PATTERN######
in the middle, we only keep the second part so that the previous line is deleted. The P
command prints the resulted pattern.
sed的代码:
sed -nr '/####PATTERN#######/!{x;1!p;x};$p;h' file
$ sed -nr '/####PATTERN#######/!{x;1!p;x};$p;h' 文件 1号线 ####PATTERN#######(第 3 行) 4号线 5号线 ####PATTERN#######(第 7 行) ####PATTERN#######(第 9 行)
GNU awk的代码:
awk '{if ($0 ~ /PATTERN/ && NR>1) {delete l[(NR-1)]}; l[NR]=$0}END {for (a in l) print l[a]}' file
$ awk '{if ($0 ~ /PATTERN/ && NR>1) {delete l[(NR-1)]}; l[NR]=$0}END {for (a in l) print l[a]}' 文件 1号线 ####PATTERN#######(第 3 行) 4号线 5号线 ####PATTERN#######(第 7 行) ####PATTERN#######(第 9 行)
这是一种方法awk
:
awk '/PATTERN/{for(;i<NR-2;)print lines[++i];i=NR;delete lines;print $0}{lines[NR]=$0}' file
$ cat file
Line 1
Line 2
####PATTERN####### (Line 3)
Line 4
Line 5
Line 6
####PATTERN####### (line 7)
Line 8
####PATTERN####### (Line 9)
$ awk '/PATTERN/{for(;i<NR-2;)print lines[++i];i=NR;delete lines;print $0}{lines[NR]=$0}' file
Line 1
####PATTERN####### (Line 3)
Line 4
Line 5
####PATTERN####### (line 7)
####PATTERN####### (Line 9)