Расширение вложенных параметров [дубликат]

Aquí hay una solución lógica que usa sedy trpero 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=3con i=npara que esto funcione para cualquier n.

Código:

# 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


Por qué esto funciona:

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
      .. ^. ^...... ^.. ^... ^. ^. ^
    • Primero reemplazamos la segunda ocurrencia, luego la tercera ocurrencia, luego la cuarta, quinta y así sucesivamente. Cuente en la secuencia que se muestra arriba para ver esto por sí mismo.
  • 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
      ... ^....... ^.... ^..... ^
    • Primero reemplazamos la 3ra ocurrencia, luego la 5ta, luego la 7ma, 9na, 11a, y así sucesivamente.
  • Cuando n = 4 :queremos reemplazar cada tercera aparición de b.

    • Primero reemplazamos la 4ª aparición, luego la 7ª, luego la 10ª, la 13ª, y así sucesivamente.
10
03.03.2021, 22:21
0 ответов

Теги

Похожие вопросы