Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a directory with several subdirectories that all contain text files. In these text files, there is a certain word that occurs over and over again, and I want to replace every instance.

My Question - How would I accomplish this from a linux commandline? I don't want to gedit every file and do a manual search/replace.

(For a bonus - is there a way to do this in a case-insensitive way?)

share|improve this question

You could use find and perl (via xargs):

find /target/directory -type f | xargs perl -pi -e 's/stringtoreplace/replacement/g'

or if you are already in the right directory

find . -type f | xargs perl -pi -e 's/stringtoreplace/replacement/g'

and if you only want to replace in, say, html files:

find . -type f -name '*html' | xargs perl -pi -e 's/stringtoreplace/replacement/g'

You don't have to use perl of course, any tool that performs search and replace operations will do, and not doubt there are several available that are less resource hungry than starting perl (which is this case is a sledge-hammer to crack a nut, but it is an example I've had stored for ages and I've no reason to find a more efficient version). My original source for the "trick" is

You can use all the options in which-ever tool you choose, so in this case the full power of Perl's regular expressions. The page linked to above has more examples, including how to search in a case in-sensitive manner.

share|improve this answer
You can use sed -i 's/string/replacement/g' in place of perl in that command. If you're using GNU sed, just add an i after the g to make it case insensitive. – Dennis Williamson Jul 10 '10 at 21:20
Also, unless you know what the names in the directories are like, you should really use the -print0 argument to find, and the -0 argument to xargs. A file with a carriage return, space, or tab in the name could cause you problems otherwise. – Slartibartfast Jul 11 '10 at 2:51
Good point on -print0/-0 - I always avoid such characters in names but even if you do you still need to be careful because others may not. – David Spillett Jul 11 '10 at 12:53

From your handle I believe you might be interested in a solution using GNU Parallel http ://

find /target/directory -type f | parallel perl -pi -e 's/stringtoreplace/replacement/ig'

This solution does the replacing in parallel and it is case insensitive. GNU Parallel does not suffer from the separator problem http :// - only if you have file names containing newlines you will need the -print0/-0 combination.

Watch the intro video for GNU Parallel:

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .