Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find and replace in multiple files on command line

How do i find and replace a string on command line in multiple files on unix?

like image 507
Vijay Avatar asked Dec 13 '09 07:12

Vijay


People also ask

How do I find and replace in multiple files?

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 that occur 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.

How do you replace a line in a file using bash?

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.


2 Answers

there are many ways .But one of the answers would be:

find . -name '*.html' |xargs perl -pi -e 's/find/replace/g' 
like image 107
Vijay Avatar answered Oct 11 '22 21:10

Vijay


Like the Zombie solution (and faster I assume) but with sed (standard on many distros and OSX) instead of Perl :

find . -name '*.py' | xargs sed -i .bak 's/foo/bar/g' 

This will replace all foo occurences in your Python files below the current directory with bar and create a backup for each file with the .py.bak extension.

And to remove de .bak files:

find . -name "*.bak" -delete 
like image 38
Stan Avatar answered Oct 11 '22 21:10

Stan