my first attempt, can’t remember how to edit a specified line in sed but you can see what I’m getting at. NOT TESTED!!!
file=infile.txt
firstoccurence=wc -l $file
lastoccurence=0
#grep gives us the line numbers where 'n' occurs in the format $file:x:how-n-occurs so we strip out the line number and find the first and last occurrence. Where x is the line number.
for i in grep -in 'n' $file
do
#remove front bit
tmp=${i#$file:}
#remove back bit
tmp=${tmp%:*}
if [ $tmp -lt $firstoccurence ]
then
firstoccurence=${tmp%:}
fi
if [ $tmp -gt $lastoccurence ]
then
lastoccurence=${tmp%:}
fi
done
#replace first occurrence with 1
some sed or awk command for line $firstoccurence
#replace last occurrence with 3
some sed or awk commad for line $lastoccurence
#replace all middle occurrence with 2
sed -i 's/n/2/g' $file
exit 0