retaining only the second line with a pattern and deleting all others

Hi,

I have a file:

5 T1AxialPremosaic ok 512 448 23 1 284000-000005-000001.dcm
6 T2_SPACE ok 256 256 176 1 465000-000006-000001.dcm
7 FLAIRmosaic ok 512 432 23 1 748000-000007-000001.dcm
8 T2_SPACE ok 256 256 1 171000-000008-000001.dcm
9 T2_SPACE ok 256 256 1 218000-000009-000001.dcm
32 T1AxialPostmosaic ok 512 448 23 1 836000-000032-000001.dcm
33 MEMPRAGE ok 256 256 704 1 408000-000033-000001.dcm
34 MEMPRAGE ok 256 256 176 1 767000-000034-000001.dcm
35 MEMPRAGE ok 256 256 1 380000-000035-000001.dcm
36 MEMPRAGE ok 256 256 1 178000-000036-000001.dcm

...and I would like to retain only the second line with the pattern MEMPRAGE (preferably using just RAGE and in a case-insensitive manner). I've tried different things with awk:

awk 'tolower($0) ~ /rage/&&c++>0 {next} 1' inputfile

but for this guy (above), I don't know how to keep only the second occurrence. I've also tried various plays on this one-liner:

awk '(substr($0,8,4)!="RAGE")||(NR<1)' inputfile

But this isn't quite right either. The bottom line is that I don't understand awk, sed or grep well enough to get it done quickly. Any help would be greatly appreciated. Thanks.

Try:

awk 'tolower($0)~/rage/&&++i==2' input
$ grep MEMPRAGE <sample8.txt | head -2 | tail -1
34 MEMPRAGE ok 256 256 176 1 767000-000034-000001.dcm

This works great, but I actually realize my mistake in writing that I wished to retain everything but the line with the second occurrence of the pattern. I would like to retain everything in the text file without the tag "RAGE", as well as the line with the second occurrence of "RAGE". So for example, this would be my ideal output:

5 T1AxialPremosaic ok 512 448 23 1 284000-000005-000001.dcm
6 T2_SPACE ok 256 256 176 1 465000-000006-000001.dcm
7 FLAIRmosaic ok 512 432 23 1 748000-000007-000001.dcm
8 T2_SPACE ok 256 256 1 171000-000008-000001.dcm
9 T2_SPACE ok 256 256 1 218000-000009-000001.dcm
32 T1AxialPostmosaic ok 512 448 23 1 836000-000032-000001.dcm
34 MEMPRAGE ok 256 256 176 1 767000-000034-000001.dcm

Any ideas on how to keep the rest of the file intact (except for lines with "RAGE")? Apologies for the follow-up here.

Try:

awk 'tolower($0)~"rage"&&++i==2||tolower($0)!~"rage"' input

You're the best. Thanks!