martes, 27 de enero de 2009

sed, borrando bloques de texto delimitado por cadenas

Tenía unos cuantos ficheros htm dentro de un directorio (pongamos como ruta /ruta/del/directorio), y quería borrar de ellos -si lo contenían- las siguientes líneas:

<div class="links">
<a href="http://peremolto.net">peremolto.net</a>
</div>


En la página de sed, el ejemplo 4.21 se ajusta casi en su totalidad a esto. Tras adaptarlo a lo mío quedó así:

nouser@nohost:~$ cat borra_delimitado.sed
# sed script to delete a block if /regex/ matches inside it
:t
/<div class="links">/,/div>/ { # For each line inside these block markers
/div>/!{ # If we are not at the /end/ marker
$!{ # nor the last line of the file,
N; # add the Next line to the pattern space
bt
} # and branch (loop back) to the :t label.
} # This line matches the /end/ marker.
/>peremolto.net</d; # If /regex/ matches, delete the block.
} # Otherwise, the block will be printed.
#---end of script---

Tal como se presenta este script sed, lo incluimos en un "for i in" que recorre los ficheros devueltos por un find

nouser@nohost:~$ for i in `find /ruta/del/directorio -name "*.htm"`; do sed -f borra_delimitado.sed -i $i; done