简体   繁体   中英

How to print all lines except the line before a pattern in file using awk

How can we do this with awk?

Input file

Line 1
Line 2
####PATTERN####### (Line 3)
Line 4
Line 5
Line 6
####PATTERN####### (line 7)
Line 8
####PATTERN####### (Line 9)

etc..

output file

Line 1
Line 3
Line 4 
Line 5
Line 7
Line 9
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.

Code for :

sed -nr '/####PATTERN#######/!{x;1!p;x};$p;h' file

$ sed -nr '/####PATTERN#######/!{x;1!p;x};$p;h' file
Line 1
####PATTERN####### (Line 3)
Line 4
Line 5
####PATTERN####### (line 7)
####PATTERN####### (Line 9)

Code for 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]}' file
Line 1
####PATTERN####### (Line 3)
Line 4
Line 5
####PATTERN####### (line 7)
####PATTERN####### (Line 9)

Here is one way with awk :

awk '/PATTERN/{for(;i<NR-2;)print lines[++i];i=NR;delete lines;print $0}{lines[NR]=$0}' file

Output:

$ 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM