简体   繁体   English

使用awk或sed删除两个模式(包括模式)之间的线

[英]Remove lines between two pattern (inclusive of the pattern) using awk or sed

My output file is as below: 我的输出文件如下:

judi#cat file
---ABC---
word1
word2
word3
word4
word5
word6
---end_ABC---

---DEF---
line1
line2
line3
line4
---end_DEF---
judi#

I need to remove the lines in between the pattern ABC and end_ABC (inclusive the pattern, then replace with new content; the new content is in a file). 我需要删除模式ABCend_ABC之间的行(包括模式,然后替换为新内容;新内容位于文件中)。

The content of the file varies, so I need to use only the pattern. 文件的内容各不相同,因此我只需要使用模式。

judi#file1
---ABC---
wordA1
wordA2
wordA3
---end_ABC---
judi#

Desired result has to be 所需的结果必须是

judi#
---ABC---
wordA1
wordA2
wordA3
---end_ABC---

---DEF---
line1
line2
line3
line4
---end_DEF---
judi#

I tried this command: 我尝试了以下命令:

sed '/ABC/,/end_ABC/{/ABC/!{/end_ABC/!d}}' file > file 2

But I get this error: 但是我得到这个错误:

sed: command garbled: /ABC/,/end_ABC/{/ABC/!{/end_ABC/!d}}
sed '/end_ABC/a ##here' file | sed '/ABC/,/end_ABC/d' | sed '/##here/r file1' | sed '/##here/d' >file2  

output 输出

judi#cat file
judi#file1
---ABC---
wordA1
wordA2
wordA3
---end_ABC---
judi#

---DEF---
line1
line2
line3
line4
---end_DEF---
judi#

a ##here is appending ##here after matching end_ABC . a ##here被追加##here匹配后end_ABC

r file1 is inserting text from file1 after finding pattern ##here . r file1在找到模式##here之后从file1插入文本。

Never use range expressions as they make trivial tasks very slightly briefer but even slightly more complicated tasks need a complete rewrite or duplicate conditions. 切勿使用范围表达式,因为它们会使琐碎的任务变得更简短,但即使是稍微复杂的任务也需要完整的重写或重复条件。 Just use a flag: 只需使用一个标志:

awk '
NR==FNR { rep = rep $0 OFS; next }
/---ABC---/ { printf "%s", rep; inBlock=1 }
!inBlock
/---end_ABC---/ { inBlock=0 }
' file1 file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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