grep or AWK help

syntax

Executive Member
Joined
May 16, 2008
Messages
9,522
Reaction score
1,642
Location
jozi
So, a little help if any one can.

I have a file which contains for example

testA
cat
testB
1
testC
cat
testD
dog

i need to search through this file, and display testX only if it DOESNT have the word cat beneath it.

so, the logic would be cat file | grep -v -B1 cat >>output.txt

now i know this doesnt work, but i need something similar.
I cant search the other way round, because the words under testX change or arent there at all. The only constant is the word cat.

So i need to search for the word cat, and then exclude the line above it.

Any help would be massively appreciated!
 
pcregrep -M '^.+\ncat$' test.txt | grep -v cat

pcregrep uses Perl compatible regular expressions.
The regex looks for a line with a carriage return and then another line with just 'cat'.
The double line results are piped to grep -v which excludes matches.
You might need to change \r to \r\n depending of the platform ( windows / unix ).

HTH
 
thanks, that kind of works, but does the opposite of what I want.

That returns
testA and testC

I want it to return testB and testD

So anywhere I find cat, i want to exclude cat and the word above.

Also note, that the string might not be a single word, so below. I still need a way to search for the word cat, and if i find it, exclude that line and the line above.

testA
this is a cat
testB
1
testC
this is a cat
testD
this is a dog
 
Hi,

Try this:

Code:
pcregrep -M '(^test.+\n)(?!^cat$)' file

hmm, that just outputs everything that has test in it and the line below unfortunately.
It doesnt output test when there isnt the word cat below
 
Hi again,

Sorry, that worked on my Mac, but I've now tested on Linux & got different results :-(

Let's try the long way:

Code:
perl -ne 'chomp; if (defined($line1) && ($_ ne 'cat')) {printf "%s\n",$line1;} $line1 = (($_ =~ m/^test/o) ? $_ : undef);' file
 
Did you come right here?
This is kinda driving me mad :mad:, trying to solve the "puzzle", as I try to do it with a one-liner in sed.
 
Why not just grep for dog and use that option to grab an extra peceeding line?... If I recall correctly the option is -B

EDIT: oh wait I see you have more than just dog as a possibility. Carry on.
 
Last edited:
The pattern matching works in this solution, but the output includes the lines containing "1" and "dog". The OP wants just "testB" and "testD" if I understand correctly.
 
Top
Sign up to the MyBroadband newsletter
X