1

我们如何用 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
4

3 回答 3

2
sed '$!N;s/.*####PATTERN####### \(.*\)/\1/;P;D' text

Output

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.

于 2013-07-22T02:31:13.617 回答
2

的代码:

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 '{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 行)
于 2013-07-22T10:16:28.437 回答
1

这是一种方法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)
于 2013-07-22T02:44:08.360 回答