Here's a perl solution (don't know how to keep indents, sorry..):
while(<>){ # Loops over standard input
if (/^# .* foo .*/x) {
s/foo/bar/;
s/^#//;
}
print;
}
Here's a perl solution (don't know how to keep indents, sorry..):
while(<>){ # Loops over standard input
if (/^# .* foo .*/x) {
s/foo/bar/;
s/^#//;
}
print;
}
Ok, ignore the removing of #'s sorted that with another function.
Just need to know how to replace foo with bar on a random line.
This sounds like what i want, but i want to save this change to file which im not sure this does...import fileinput
for line in fileinput.FileInput("file.name", inplace=1): #do inplace editing..
if line[0] == '#' and "foo" in line:
line = line.replace("foo","bar")
print line
Using ubuntu offline?
Want to install new programs?
Check out wubdepends
If Stupidity got us into this mess,
then why can’t it get us out?
Google is your friend:
http://pydoc.org/2.4.1/fileinput.html
Optional in-place filtering: if the keyword argument inplace=1 is passed to input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file. This makes it possible to write a filter that rewrites its input file in place. If the keyword argument backup=".<some extension>" is also given, it specifies the extension for the backup file, and the backup file remains around; by default, the extension is ".bak" and it is deleted when the output file is closed.
This is why I love python - often used functionality is neatly packed, ready to be used.
Thanks ghostdog74, I learned another neat library function.
Last edited by pmasiar; January 3rd, 2007 at 09:17 PM. Reason: Thanks ghostdog74
Bookmarks