Find in files and replace in files in Linux

If you are looking for functionality similar to notepad++ functionality of replacing a string in all the files in a certain folder, Look no more, in linux this is a simple command

Assuming you are on the command line and the directory containing the files is the active one (cd)

the following line will replace foo with bar in all files on the current root directory but not in subdirectories

sed -i -- 's/foo/bar/g' *

If you want it to go recursively into sub directories, you can combine the above with the find command

 find . -type f -exec sed -i 's/foo/bar/g' {} +

if you want sed to backup the files before it does the replace, use the following command, you can replace the .bak with anything you like

sed -i.bak -- 's/foo/bar/g' *

Leave a Reply

Your email address will not be published. Required fields are marked *