replace nth instance of string

Hi all,
I have file with following content

...........................
..........TEST..........
..........TEST..........
.....................
.....TEST..........
.....................
.....................
.....TEST..........

I want to replace nth "TEST" with "OK" using sed/awk/perl....

tried sed 's/TEST/OK/3' filename...but it will replace nth instance of each line....

Thanks and Regards,
uttam hoode

Hi Uttam,

I have some suggestions for your problem.

  1. Make your file with a single line, such that all the 'TEST' pattern occurs in a single line. You can use tr command to do this.
tr '\n' ';' < inp.txt > temp1.txt
  1. Then use sed command to replace the nth occurrence of the 'TEST' pattern.
sed 's/TEST/OK/5' temp1.txt > temp2.txt
  1. Then split the single line using the same tr command.
tr ';' '/n' < temp2.txt > out.txt

It may be a very long and tedious process, but I think it will help you to proceed.

Regards,
Chella.

#   cat infile | nawk '/TEST/{n+=1}{if (n==3){sub("TEST","OK",$0)};print }'
...........................
..........TEST..........
..........TEST..........
.....................
.....OK..........
.....................
.....................
.....TEST..........

HTH

HI chella and Tytalus,
Thanx for the solution.....

Tytalus can u please give me a sed quivalent for this command?....in sed i can use inline edit option (-i) and can modify the file without using cat,pipe or redirection...

Regds,
uttam

nawk -v p=$1 'BEGIN{n=1}
$0 !~ /TEST/{print}
$0 ~ /TEST/ {
if (n!=p)
{
	n=n+1
	print $0
}
else
	
{
	sub(/TEST/,"OK",$0)
	print $0
	n=n+1
}
}' filename