Thursday, September 26, 2013

How to replace string in the project using terminal in Ubuntu?

We want to replace the string "regexp" with the string "replacement" in the terminal.
Let's say our project path is /home/www/project_name.
Actually regexp string is a regular expression pattern for our string.

This command works right:
cd /home/www/project_name
find . -type f -print0 | xargs -0 sed -i 's/regexp/replacement/g'
Let's see what the command means.
I will translate it to the normal language for human beings.

Go to my project folder:
cd /home/www/project_name Find all files (-type f) in my project folder:
find . -type f Use \0 delimiter (and not whitespace) to separate between the found pathnames in the output.
(We don't want whitespaces, because filenames can contain whitespaces and we will not be able to separate between pathnames).
-print0 This is a pipe. It means all the output that we have got before this sign "|" becomes an input for a next command (xargs in our case).
| xargs takes the output (pathnames that the command find found).
We use -0 because pathnames are terminated by \0 (instead of by whitespace). We know because we specified (find -print0).
xargs -0 sed - stream editor for filtering and transforming text.
-i allows to edit files in place.
-g replace all matches, not just the first match.
Replace our "regexp" with "replacement". sed -i 's/regexp/replacement/g'