root | 15 May 17:21

(no subject)

hi ,i am working to replace three lines in a httpd.conf file using
regular expression.i am able to change only one among them but while
replacing other i am not geeting good idea to replace all the three
lines just in a single script ,,my script is like

 #!usr/bin/python

import sys
import os
import re
import  string

def replace_file(file,search,replace):
	cregex=re.compile(search)
	for current_line in file:
		if cregex.search(current_line):
			current_line=re.sub(search,replace,current_line)
			print current_line
		else:
			print current_line
		
		
def main():
	file =open("/root/Desktop/httpd.conf").readlines()
	replace_file(file,'User apache ' , 'User myuser ')
	#replace_file(file,'Group apache','Group myuser')
	#replace_file(file,DirectoryIndex\ index.html\ index.html.var,DirectoryIndex\ index.html\
index.html.var\ login.html)
	
		
(Continue reading)

Kent Johnson | 15 May 17:51
Gravatar

Re: (no subject)

On Thu, May 15, 2008 at 11:22 AM, root <jatinder.singh2 <at> wipro.com> wrote:
> hi ,i am working to replace three lines in a httpd.conf file using
>  regular expression

You don't need regex for this, you are replacing plain strings. I
would read the entire file, change the strings and write it out again.
For example,

path = "/root/Desktop/httpd.conf"
f = open(path)
data = f.read()
f.close()
for search, replace in [
       ('User apache ' , 'User myuser '),
       ('Group apache','Group myuser'),
       ('DirectoryIndex\ index.html\ index.html.var','DirectoryIndex\
index.html\ index.html.var\ login.html')
    ]:
    data.replace(search, replace)

f = open(path, 'w')
f.write(data)
f.close()

This replaces the file in place, if you want to make a backup it will
be a little more complex.

A few other notes:
- don't use 'file' as a variable name, it shadows the builtin file() function
- I'm not sure what the \ in your search string are for but they are
(Continue reading)


Gmane