Wednesday, March 11, 2009

Search and Replace across multiple files

Bookmark and Share

Most of us stuck at some point of time to replace a string in multiple files.

How do we do this? Write a few lines of code to do this job (or possibly a script). We have got perl to help us out to do this same task in single line..

# perl -pi -i.orig -e 's/scalar/vector/g' *.xml

If we fire this CLI in current directory then it will replace all occurrences of word ‘scalar’ to ‘vector’ in all .xml files while backing up all original ‘files.xml’ file and renaming them to ‘files.xml.orig’.


  1. looks interesting. tomorrow i'll try this and if worked correctly, 'll come back to comment again !!!

  2. This will be very useful in day to day work.

  3. will this work in windows ??

  4. It works on Unices but not sure on windows. Limitation may be the wildcards that can be accepted by perl CLI.

    When I tried then I received following message,
    c:\>perl -pi -i*.orig -e 's/scalar/vector/g' *.xml
    Can't open *.xml: Invalid argument.

    However, exclusion of wild card such as following CLI works perfectly.

    c:\>perl -pi -i*.orig -e 's/scalar/vector/g' test.xml

  5. For windows, you can try using tool called (WinGrep). It will help you to search and replace across multiple files


Your valuable comments are welcome. (Comments will be moderated.)