[Python-de] String in Datei ersetzten
Christopher Arndt
chris.arndt at web.de
Wed Feb 6 15:24:59 EST 2002
Angefügt ein Beispiel Skript. Geht bestimmt auch kürzer, mir war hier
eher die Klarheit wichtig.
Felix Seeger wrote:
> Nun ich habe eine Datei.
> Ich möchte in dieser Datei ca. 5 aufeinander folgende Zeilen auskommentieren
> bzw. mit einem Kommentar versehen
>
> Beispiel:
>
> <VirtualHost IP>
> ServerAdmin mail
> DocumentRoot /var/www/domain
> ServerName NAME
> ErrorLog logs/host.DOMAIN-error.log
> CustomLog logs/host.DOMAIN-access.log common
> </VirtualHost>
>
> Wenn das Programm fertig ist soll es so aussehen:
>
> #<VirtualHost IP>
> # ServerAdmin mail
> # DocumentRoot /var/www/domain
> # ServerName NAME
> # ErrorLog logs/host.DOMAIN-error.log
> # CustomLog logs/host.DOMAIN-access.log common
> #</VirtualHost>
>
>
> Das ganze auch umgekehrt.
-------------- next part --------------
import re, sys
start_re = re.compile(r'^\s*<VirtualHost.*?>\s*$')
end_re = re.compile(r'^\s*</VirtualHost\s*?>\s*$')
f = open(sys.argv[1])
in_match = 0
for line in f.readlines():
if not in_match:
match = start_re.search(line)
if match:
in_match = 1
if in_match:
sys.stdout.write('#' + line)
# to remove comment chars, change regexes and use:
#sys.stdout.write(line[1:])
match = end_re.search(line)
if match:
in_match = 0
else:
sys.stdout.write(line)
More information about the Python-de
mailing list