Find and Replace Text in Multiple Files

(0 votes, average 0 out of 5)

Sometimes it is useful to be able to replace a certain piece of text in multiple files, even across multiple folders. Opening each file and using find/replace is tedious. Fortunately, there is a much easier way using the sed and grep utilities. For Windows users, please install Cygwin to get these programs on your system. Linux and Mac OS X users will already have these programs pre-installed.

Launch a terminal window, and cd to the root directory where all of these files and folders exist. Once in the correct directory, type the following:

 

sed -i ‘s/textToFind/replacementText/g’ `grep -ril ‘textToFind’ *`

 

This command will recursively replace any instances of textToFind with replacementText in all documents in the current folder and sub folders. This command works by first searching for the names of all the files containing textToFind using grep. The output of this command is piped inline to the input for the sed command, which does the actual replacement. This inline substitution is accomplished with the `` quotes (probably to the left of the 1 key on your keyboard). This is a special syntax in the BASH Shell which causes the contents of whatever is inside the `` to be executed and the results to be put in its place.

To do a simpler find and replace on only 1 file, use the following syntax:

 

sed -i ‘s/textToFind/replacementText/g’ /path/to/file.txt

 

 

Partner Links:
Last Updated on Tuesday, 10 August 2010 18:18  
Related Articles

» How to edit remote files with WinSCP and Notepad++ (or any other editor..)

Have you ever wondered how to edit a remote file in a Linux environment while you are working in a windows environment? Or maybe just want to edit a file directly from an FTP client? If so, WinSCP is for you!  is an open source FTP, SFTP, and SCP client with a graphical interface. You can download the latest version of WinSCP here: . In this tutorial, I will be using (which can be found here: ). However, you may substitute any text editor you would like! To use Notepad++ with...

» How to Quickly Move Windows to the Side of the Screen Using a Hotkey in Windows

There are many cases where a focused window may be in your way, or maybe you just want to put the window on one of the sides of the screen. This can be done very easily by focusing the window you would like to move, holding down the windows key, and using the arrows to move to each side of the screen. This hotkey also works with multiple displays!

» Correcting Internet Explorer 8's Favorites Bar Icon Width

If you're using Internet Explorer 8 and find that folders and web links dragged to your favorites bar have become icons or short titles only and you want full titles, there is a simple fix!Right click on the yellow folder icon.Goto Customize Title Widths.Select Long Titles.Now your favorites bar folders and web sites will resize to their full width.