Linux command to find and replace strings in multiple files

Ever found yourself having to find and replace multiple strings, in multiple files, in multiple directories?

Well, here is your new favorite Linux command:

Even if you only need to find/replace in one document, this works like a charm.

This is a UNIX command, so should work on OS X in addition to Linux, but I have not tested OS X to confirm. For Windows you can use Notepad++ which has an option for this, but it’s a graphical application and has more steps involved.

You use this command by replacing stringyouwanttofind (two occurrences) with the string/keyword/phrase you want to find in the file/files, stringyouwanttoreplacewith (one occurrence) with the string/keyword/phrase you want to replace the found string with, and somedirectory/ with the directory you want to search in (simply use a period . if you want to search inside the current directory).

Then the grep command will go and find the string in the specified directory (together with subdirectories), then pass along (pipe) the found files to the xargs and sed commands which together works their magic to replace the original string with the new string (stringyouwanttoreplacewith).

To find a way to do this from the command line in Linux, I ended up googling and finding several articles and posts about it. The credit for this command goes to @enoex and his blog post.

Did you already know about this command (or a similar one), or do you have some other tool you swear to for this? Please comment below.

 

Robert Axelsen

Robert Axelsen is a JavaScript Developer at Sipwise GmbH, and a passionate "life-long student" of all things code and dev. When he is not busy with code or blogging, he tweets, runs a local Free Code Camp group in Vienna, spends time with his amazing wife and two daughters, and keeps up to date on all things tech. You can read more on his website.

 

Leave a Reply

%d bloggers like this: