Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a string with another string in all files below my current dir

Tags:

string

bash

sed

How do I replace every occurrence of a string with another string below my current directory?

Example: I want to replace every occurrence of www.fubar.com with www.fubar.ftw.com in every file under my current directory.

From research so far I have come up with

sed -i 's/www.fubar.com/www.fubar.ftw.com/g' *.php 
like image 591
KRB Avatar asked Sep 16 '11 20:09

KRB


People also ask

How do I replace text in all files in a folder?

Remove all the files you don't want to edit by selecting them and pressing DEL, then right-click the remaining files and choose Open all. Now go to Search > Replace or press CTRL+H, which will launch the Replace menu. Here you'll find an option to Replace All in All Opened Documents.

How do you replace a string with another string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do you replace a string that occurs multiple times in multiple files inside a directory?

s/search/replace/g — this is the substitution command. The s stands for substitute (i.e. replace), the g instructs the command to replace all occurrences.

Which command is used to replace a string by a new one?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.


1 Answers

You're on the right track, use find to locate the files, then sed to edit them, for example:

find . -name '*.php' -exec sed -i -e 's/www.fubar.com/www.fubar.ftw.com/g' {} \; 

Notes

  • The . means current directory - i.e. in this case, search in and below the current directory.
  • For some versions of sed you need to specify an extension for the -i option, which is used for backup files.
  • The -exec option is followed by the command to be applied to the files found, and is terminated by a semicolon, which must be escaped, otherwise the shell consumes it before it is passed to find.
like image 74
martin clayton Avatar answered Sep 17 '22 12:09

martin clayton