McM
mcm@noway.es
Contact me: noway.es
Contact me

How To Substitute Strings of several files

Here I present a simple solution to substitute a string for other one in a unix enviroment.

Imagine you have several files with a string you want to substitute. In this case, I have several python files and I want to comment the logger.

First of all, extract all the files to a files.txt like this:

mcm@McM:/tmp$ find miki/ -name "*.py" > files.txt

files.txt will have all the .py files in the miki directory:

mcm@McM:/tmp$ more files.txt
miki/gestion_super2.py
miki/gestion_super3.py
miki/gestion_super.py

To substitute a string for other one I can use the command sed as follows:

mcm@McM:/tmp$ sed -i '''s/logging.debug/#logging.debug/g' `cat files.txt`

This command sustitutes logging.debug for #logging.debug. This way I have commented the logger in all the py files.

Some other sed commands:

mcm@McM:/tmp$ sed 's/logging.debug/#logging.debug/g' files.txt > /tmp/temp.txt

This will substitute logging.debug for #logging.debug and put the output to a temporal file temp.txt.
Depending of what you want the first solution could be the nicest way to change a word in different files.

Share it!

Twitter Gmail Delicious Google Bookmarks Hotmail Yahoo Mail Share/Bookmark