Replace Text in Multiple Files

Thursday, September 01, 2011 »

Did you ever change your mind and want to change the name of one variable in your complete code base? Or change a name in all documents? You want to change one string with another in all files in a certain directory.

Linux gives you the right tools. There are multiple options.

Assume that in all files with the extention cpp (that are in the directory PATH/TO/DIRECTORY) we want to change the string OLDSTRING with NEWSTRING

Pipeing from find to perl

or if you want to make a backup before changing the files (and starting from Perl):

or (without making a backup and starting from Perl)

Example (exchange in all files):

While Perl would be in most repositories and is most probably installed, some machines with minimal installations (such as servers) might not have Perl and it might not be advisable to tinker with them. One fall-back solution would be to use the good old sed;

Probably it is the easiest to create a small file (eg. ch_all.sh) with the following content:

1
2
3
4
5
6
\#!/bin/bash
     for fl in *.cpp; do  #comment
     mv $fl $fl.old
     sed 's/OLDSTRING/NEWSTRING/g' $fl.old > $fl
     rm -f $fl.old
     done

Of course you should not forget to make the file executable and execute it: