Aquí hay una solución lógica que usa sed
y tr
pero debe escribirse en un script para que funcione. El siguiente código reemplaza cada tercera ocurrencia de la palabra especificada en el comando sed
. Reemplace i=3
con i=n
para que esto funcione para cualquier n
.
# replace new lines with '^' character to get everything onto a single line
tr '\n' '^' < input.txt > output.txt
# count number of occurrences of the word to be replaced
num=`grep -o "apple" "output.txt" | wc -l`
# in successive iterations, replace the i + (n-1)th occurrence
n=3
i=3
while [ $i -le $num ]
do
sed -i '' "s/apple/lemon/${i}" 'output.txt'
i=$(( i + (n-1) ))
done
# replace the '^' back to new line character
tr '^' '\n' < output.txt > tmp && mv tmp output.txt
Supongamos que el archivo de texto es a b b b b a c a d a b b b a b e b z b s b a b
.
Cuando n = 2 :queremos reemplazar cada segunda aparición de b
.
a b b b b a c a d a b b b a b e b z b s b a b
.. ^. ^...... ^.. ^... ^. ^. ^
Cuando n = 3 :queremos reemplazar cada tercera ocurrencia de b
.
a b b b b a c a d a b b b a b e b z b s b a b
... ^....... ^.... ^..... ^
Cuando n = 4 :queremos reemplazar cada tercera aparición de b
.