Linux – Multiple search and replace actions in one large text file

find and replacelinuxsedvim

I have a big text file (about 2GB). I want to do five search and replace actions on the same file, and would like to do this in one command. Normally I use vim, open the file, do one replace action, then the next, etc. There is one catch, as I noticed that after three or four searches vim crashes because of memory issues.

Here are two examples of the command I use in Vim:

:%s/www\.abcdef/www.test.abcdef/g 
:%s/www\.klmnop/www.test.klmnop/g

What is the best way to handle this?

Best Answer

I would use sed like this :

sed -i "s/www\.abcdef/www.test.abcdef/g;s/www\.kmlnop/www.test.klmnop/g;" yourfile.txt

-i option stands for "in place" replacement. You can tell sed to create a backup of your file providing an extension to this option ( -i.bak will backup yourfile.txt as yourfile.txt.bak ).

Related Question