Search and Replace across multiple files

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’.

Note: We at TechSutram take our ethics very seriously. More information about it can be found here.
Mandar Pise Opinions expressed by techsutram contributors are their own. More details

Mandar is a seasoned software professional for more than a decade. He is Cloud, AI, IoT, Blockchain and Fintech enthusiast. He writes to benefit others from his experiences. His overall goal is to help people learn about the Cloud, AI, IoT, Blockchain and Fintech and the effects they will have economically and socially in the future.

5 comments:

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

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

    ReplyDelete
  3. 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

    ReplyDelete
  4. For windows, you can try using tool called http://www.wingrep.com/download.htm (WinGrep). It will help you to search and replace across multiple files

    ReplyDelete

    Your valuable comments are welcome. (Moderated)