[Ilugc] Multiple find and replace in a text file

  • From: tshrinivasan@xxxxxxxxx (Shrinivasan T)
  • Date: Mon, 9 Dec 2013 11:27:29 -0800

Found some similar answer here too.
http://superuser.com/questions/618407/multiple-search-and-replace-actions-in-one-large-text-file

<quote>
If you have many more search patterns, you could save them in a file
and read the substitutions from there. For example, say these are the
contents of replacements.txt:

www\.abcdef www.test.abcdef
www\.klmnop www.test.klmnop

You can then read a list of N replacements and replace them with this:

while read from to; do
  sed -i "s/$from/$to/" infile.txt ;
done < replacements.txt

NOTES:

This assumes your search strings do not contain spaces and any strange
characters need to be escaped in replacements.txt.
It will run one sed per replacement which may take a while if you have
many replacement operations.
It can deal with an arbitrary number of replacements (thousands or
millions or whatever) as long as you don't mind that it will take a
bit more time.

Another option would be to write the above as a sed script:

s/www\.abcdef/www\.test\.abcdef/g;
s/www\.kmlnop/www\.test\.klmnop/g;
s/aaaa/bbbb/g;
s/cccc/dddd/g;
s/eeee/ffff/g;

You can then run the script on your file and it will make all the
replacements in one go:

sed -f replace.sed infile.txt


</quote>


Exploring these.

-- 
Regards,
T.Shrinivasan


My Life with GNU/Linux : http://goinggnu.wordpress.com
Free E-Magazine on Free Open Source Software in Tamil : http://kaniyam.com

Get CollabNet Subversion Edge :     http://www.collab.net/svnedge

Other related posts: