Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace text in all files of a linux directory

I have a website directory where I need to change all hardcoded links from one domain to another. Looking for a single (grep? sed?) bash command that will allow me to change all occurrences of text in all files in the directory?

like image 207
Yarin Avatar asked Nov 03 '10 18:11

Yarin


People also ask

How do you replace a word in all files in a directory Linux?

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.

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 search for a word in all files in a directory in Linux?

Search All Files in Directory To search all files in the current directory, use an asterisk instead of a filename at the end of a grep command. The output shows the name of the file with nix and returns the entire line.


2 Answers

The following will do it:

sed -i 's/old_link/new_link/g' file... 

Don't forget to escape any slashes, dots, and any other regex special chars in the link addresses with a backslash.

like image 90
Michael Goldshteyn Avatar answered Oct 14 '22 00:10

Michael Goldshteyn


Also, try:

perl -p -i -e <regex> <folder> 
like image 24
Daniel Pereira Avatar answered Oct 14 '22 00:10

Daniel Pereira