[Tutor] best search/replace method?

Luke Paireepinart rabidpoobear at gmail.com
Wed Apr 25 23:30:14 CEST 2007


Rikard Bosnjakovic wrote:
> On 4/25/07, John Washakie <washakie at gmail.com> wrote:
>
>   
>> cat raw.html |
>> sed 's/ImagePathReplaceMe/NewPathToImage/g' |
>> sed 's/TitleReplaceMe/NewTitle/g' > new.html
>>     
>
> One line's sufficient:
>
> sed -e 's/ImagePathReplaceMe/NewPathToImage/g;s/TitleReplaceMe/NewTitle/g'
> raw.html > new.html
>
>   
>> However, this is going to be part of an Plone product so I want to use
>> Python. What is the best method to accomplish this?
>>     
>
> d = open("raw.html").read()
> d.replace("ImagePathReplaceMe", "NewPathToImage")
> d.replace("TitleReplaceMe", "TitleReplaceMe")
>   
replace isn't a modifying function, so you'd have to do something like this:
d = open("raw.html").read()
x = open("new.html","w")
x.write(d.replace("ImagePathReplaceMe", 
"NewPathToImage").replace("TitleReplaceMe", "TitleReplaceMe"))
x.close()

or just store the strings after replacement in a temporary variable.
> x = open("new.html", "w")
> x.write(d)
> x.close()
>
> Untested.
>
>
>   



More information about the Tutor mailing list