Command line search and replace?
by Pascal Opitz on September 30 2008, 06:24
So I'm asking around for the best way to do search and replace in command line ... I have to copy files into another folder, but replace one word.
Tom pointed me towards using perl:
cp ./source/* ./destination/
cd ./destination/
perl -pi -e 's/foo/bar/' *
Justin in contrast uses sed, and a loop:
cd ./source
for A in `ls`; do echo sed 's/foo/bar/' $A > ./destination/$A; done;
Which brought me to finally look into the man pages for sed , the linux stream editor. Apparanetly the -i flag enables in-place editing there as well, and you could do something like tom did with sed:
cp ./source/* ./destination/
cd ./destination/
sed -i '' 's/foo/bar/' *
Initially, trying the -i flag, I got weird warnings like this:
sed: 1: "index.shtml": command i expects followed by text
This is due to the missing extension that you need to provide for the -i flag, in the case above I used '' to not create any backup files. If you provide '.bak' it will create backup files, i.e. index.shtml.bak before editing.
Happy search and replace!
Comments
http://txt.binnyva.com/2007/12/using-m4-command/
by Binny V A on September 30 2008, 13:09 #