PDA

View Full Version : tool to subsitute foo by bar in multiple files



mezhaka
March 16th, 2007, 11:01 PM
hello, ubuntu users!

i have a bunch of python files and i'd like to change the name of a particular variable throughout many files in a particular directory, but i has to be a command line tool. can anyone suggest one? i could have written a perl oneliner for that. but i guess it's a solved problem, i'm just not aware of the solution.

23meg
March 16th, 2007, 11:03 PM
Check out sed.

dwblas
March 16th, 2007, 11:45 PM
(I) have a bunch of python filesIt can also be done pretty easily using Python. There are threads in this forum about doing similar things using SED, per the above post, if that is your script of choice.

johnnymac
March 17th, 2007, 02:39 AM
sed is your friend.....

cat *.py |sed 's/foo/bar/g'

ghostdog74
March 17th, 2007, 05:11 AM
hello, ubuntu users!

i have a bunch of python files and i'd like to change the name of a particular variable throughout many files in a particular directory, but i has to be a command line tool. can anyone suggest one? i could have written a perl oneliner for that. but i guess it's a solved problem, i'm just not aware of the solution.

i assume you know Python


import glob,os
yourdir = os.path.join("/","test")
os.chdir(yourdir)
for fi in glob.glob("*foo*.py"):
newfile = fi.replace("foo","bar")
os.rename(fi,newfile)

smartbei
March 17th, 2007, 11:32 AM
A decently powerful tool I use when I feel like a gui and more features (like undoing changes - I think...) is KFileReplace, available through synaptic.

EDIT - sorry missed that it has to be command line.

tomchuk
March 17th, 2007, 03:57 PM
sed -i -e 's/foo/bar/g' *.py

amanda
December 5th, 2007, 03:18 AM
tomchuk,

I'm embarrassed by how long I've been trying to sort that out.

Thank you.