I had to replace a string in multiple files for one of my project and i have to do it recursively because the files in the inner directories also contains that word. I intented to do this using sed command in linux, rather than going for the options available in the editor.Lets see how to do it.

This work contains 3 parts,
  1. Move to the project directory
  2. Decide the strings you going to find and replacement word
  3. Execute the command.
The whole command looks like this,
find . -type f -exec sed -i 's/\/wds/\/labs\/wds/g' {} +

Above command searches for "" and replaces it with "". The backword slash ( \ ) used in the command to escape forward slashes ( / ) in the search and replace words.

More simple version of the command looks like this,
find . -type f -exec sed -i 's/wds/webdevelopmentscripts/g' {} +

Which searches for the word "wds" and replaces it with "webdevelopmentscripts". Incase if you want to replace those words in files which has some specific extension, like ".php", we can modify above command like below:
find . -type f -name "*.php" -exec sed -i 's/wds/webdevelopmentscripts/g' {} +

It looks into files which has .php extension and replace the word if found. We have seen how to use the find & sed command to find and replace a string in all files or files with specific extension.

Now Lets look at the options used in the command for the better understanding.

 Find    - Command used to search files based on criteria
 .    - Indicates search files in the current directory. If you want to search in other directory give the path of the directory here.
 -type f     - Tells the command to look into only the files
 -name "*.php"   - Tells the find command to look into files only with *.php" extension
 -exec    - Process the output of find command using sed
 sed   - Stream editor, performs text operations on the go. It has lots of commands, here we used "s" - means subsititue, which is a search and replace functionality
 -i    - Search without case sensitive
 s/wds   - Search for "wds"
 /webdevelopmentscripts/g   - Replacement word, "g" indicates replacing all occurences.

Comments (0)
Leave a Comment

loader Posting your comment...