
특정 단어를 포함하지 않는 두 패턴 사이에 일부 텍스트를 인쇄하고 싶습니다.
입력 텍스트는
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
:
1:
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