我想在两个模式之间打印一些不包含特定单词的文本
输入文本是
HEADER asdf asd
asd COW assd
TAIL sdfsdfs
HEADER asdf asd
sdfsd DOG sdfsdfsdf
TAIL sdfsdfs
HEADER asdf asd
sdfsd MONKEY sdfsdfsdf
TAIL sdfsdfs
需要的输出是
HEADER asdf asd
asd COW assd
TAIL sdfsdfs
HEADER asdf asd
sdfsd MONKEY sdfsdfsdf
TAIL sdfsdfs
从概念上讲,需要这样的东西
awk '/HEADER/,!/DOG/,TAIL' text
答案1
和perl
:
perl -0777 -lne 'print for grep !/DOG/, /^HEADER.*?TAIL.*?\n/mgs' your-file
和awk
:
awk '! inside {if (/^HEADER/) {inside = 1; skip = 0; content = ""} else next}
/DOG/{skip = 1; next}
! skip {content=content $0 "\n"}
/^TAIL/ {if (!skip) printf "%s", content; inside = 0}' your-file
答案2
如果这里没有其他限制你的脚本
sed '/^HEADER/{:1;N;/TAIL/!b1;/DOG/d}' text
只是为了好玩: 的其他变体awk
:
一:
awk '
BEGIN{prn=1}
/^HEADER/{block=1}
block{
if(/DOG/)
prn=0
if(!/^TAIL/){
line=line $0 "\n"
next
}
}
prn{print line $0}
/^TAIL/{
block=0
prn=1
line=""
}
' text
二:
awk '
/^HEADER/{
line=$0
while(!/TAIL/){
getline
line=line "\n" $0
}
if(line !~ /DOG/)
print line
next
}
1' text