1

I want to print some text between two patterns which doesn't contain a particular word

input text is

HEADER asdf asd 
asd COW assd
TAIL sdfsdfs
HEADER asdf asd
sdfsd DOG sdfsdfsdf
TAIL sdfsdfs

HEADER asdf asd
sdfsd MONKEY sdfsdfsdf
TAIL sdfsdfs

output needed is

HEADER asdf asd
asd COW assd
TAIL sdfsdfs

HEADER asdf asd
sdfsd MONKEY sdfsdfsdf
TAIL sdfsdfs

conceptually something like this is needed

awk '/HEADER/,!/DOG/,TAIL' text 
  • The empty line in your output is not between HEADER and TAIL in your input file so be more specific as to what should be preserved in the output... – don_crissti May 21 '15 at 13:37
  • Can you HEAD or TAIL lines contain DOG? If yes, is that ground for exclusion? – Stéphane Chazelas May 21 '15 at 15:39
  • HEAD OR TAIL will not contain DOG. I just have to skip the whole segments(between HEAD and TAIL,both inclusive) if there is a DOG between the HEAD and TAIL. – user3905367 May 22 '15 at 3:22
2

With perl:

perl -0777 -lne 'print for grep !/DOG/, /^HEADER.*?TAIL.*?\n/mgs' your-file

With 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

If there is no other limitation here your script

sed '/^HEADER/{:1;N;/TAIL/!b1;/DOG/d}' text 

Just for fun other variants of awk:
one:

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

two:

awk '
    /^HEADER/{
        line=$0
        while(!/TAIL/){
            getline
            line=line "\n" $0
            }
        if(line !~ /DOG/)
            print line
        next
        }
    1' text

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.