remove/replace text/path in config file.

Lot of times I end up changing a particular text in config file to some other text. And when I have to do it for multiple files, all files having the text in multiple places, I end up opening the files in vim and then doing a globlal replace. But this is not efficient so I cam up with some one liners to do this for me. For removing any occurance of text in all files in the directory :

for i in $(grep -l \’text-to-remove\’  *) ; do sed \’s@text-to-remove@@\’ $i >${i}.new; mv $i{,.bak}; mv $i{.new,}; done

And if you want to replace the text then the same command with little change in sed command:

for i in $(grep -l \’text-to-replace\’ *) ; do sed \’s@text-to-replace@new-text@\’ $i >${i}.new; mv $i{,.bak}; mv $i{.new,}; done

Quickly search and replace string with Regular expression in multiple files using perl

for i in *; do perl -p -w -e \’s/a(.*)b.*/d$1e/g\’  $i > temp/$i; done

for i in *; do perl -pi -w -e \’s/a(.*)b.*/d$1e/g\’  $i ; done

The first one can be used when you want to preserve the original file. The redirection will cause the file with replaced string to be written to the new location in the temp directory. Modify the same according to your needs.

The second can be used to modify the files in-line. Causing overwriting the original file.

Explanation of the RE : s/a(.*)b.*/d$1e/g

s – substitue

s(.*)b.* –> match anything starting with and store the substring upto b into $1 for further use. Continue matching from b until end of line

d$1e –> replace the original string with d concatened with $1 from the match above and then with e.