Deleting line with range check in awk

Consider a input.txt as:

country=india
ram
ajit
sham
vijay                //need to be removed
country=india
suman
tharan
raju

what i did is:

awk '$0~pat {n=NR+4} NR!=n' pat='country=india' input.txt > output.txt

My looking to the above code is between any two country=india , number of lines should be 3 NR == 3

I'm not able do this, help me with this.

Try :

$ awk 'FNR != s; $0 ~ pat{s = FNR + 4}' pat='country=india' file

input:

country=india
ram
ajit
sham
vijay                          //need to be removed
country=india
suman
tharan
raju
country=india
suman
tharan
raju

Above code's output:

country=india
ram
ajit
sham
country=india
suman
tharan
raju
suman
tharan
raju

So what do you expect from your new input ?

As you can see there is a line missing in #2 output. 'country=india'

My looking is actually between any two 'country=india' , NR = = 3

With your original input I get this

$ cat file
country=india
ram
ajit
sham
vijay                //need to be removed
country=india
suman
tharan
raju

$ awk 'FNR != s ;$0 ~ pat{s = FNR + 4}' pat='country=india' file
country=india
ram
ajit
sham
country=india
suman
tharan
raju

Please give proper description along with expected output.

---------- Post updated at 02:57 PM ---------- Previous update was at 02:52 PM ----------

Try this with your new input :

$ awk 'p,p{if($0 ~ p){print;if(k>0){k=0}next}else{if(++k !=4)print}}' p='country=india' file
1 Like

Yes. Its working fine now. Thanks!

I can see you updated first post

$ awk 'p,p{if($0 ~ p){print;if(k>0){k=0}next}else{if(++k <= 3)print}}' p='country=india' file
1 Like

I can't see why your first attempt should not work on your sample files. Exception: if there's more than one line to remove. In that case, try

awk '$0~pat {n=NR+3} NR<=n'  pat='country=india' file

Should your pattern show up later and not in line 1, set n to a large number:

awk '$0~pat {n=NR+3} NR<=n' n=1E20 pat='country=india' file