Replace second occurrence only

HPUX /bin/sh (posix)

I have a file as such

cat dog mouse
deer elk rabbit
mouse rat pig

I would like to replace the second occurrence of mouse in this file with mouse2. The rest of the file has to stay exactly as is. I'm not sure exactly where mouse might be (could be first,second,third field).

TIA!!!!!!

Put this code in mouse.awk

/mouse/{
   mcount++
   if(mcount == 2){
       sub("mouse","mouse2",$0)
   }
}

{print}

awk -f mouse.awk animals.txt

So what happens if the file has this:

cat mouse mouse

the poster said they wanted the second occurrence. this does that. if you need all occurrences of mouse changed on the line where the second occurrence is found then change sub to gsub.

I think I was not clear. I meant, for "cat mouse mouse", the second "mouse" on this line also counts as a second ocurrance. So shouldn't that change to "cat mouse mouse2"?

This'll take care of it:

awk -f mouse.awk RS=" " ORS=" " animals.txt
$ cat animals.txt 
cat dog pig 
deer elk rabbit
mouse mouse mouse

$ awk -f mouse.awk RS=" " ORS=" " animals.txt 
cat dog pig 
deer elk rabbit
mouse mouse2 mouse