2

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 
3
  • 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... Commented May 21, 2015 at 13:37
  • Can you HEAD or TAIL lines contain DOG? If yes, is that ground for exclusion? Commented May 21, 2015 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. Commented May 22, 2015 at 3:22

2 Answers 2

3

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.