Search and replace on multiple files

Making some kind of text search and replace operations on a single or multiple files is a trivial task for every Linux system admin or even normal user. There are different ways for this, we just want to describe two of them.

If you already familiar with perl and know a little regular expression syntax, you can use one-line embedded perl usage:

perl -pi -e 's/search/replacement/g;' *.txt

or combine with find and xargs:

find -name "*.html" | \ 
      xargs perl -pi -e 's/search/replacement/g;'

You can use all the power of regular expressions and perl to further improvements.

If you found above usage a little complex, there is also a simple utility named replace which comes with mysql-client package. Common usage of replace as follow:

replace from to from to from to ... -- files

You can replace multiple texts to their replacements same time, when you finish writing your from-to replacements, you have to put a -- characters and after that you have to provide file or file list (like *.txt). Here a simple example:

replace mkae make meka make amke make -- *.sh

Above commands corrects all three typing error of “make” in the files end with .sh