Mayfield Global Knowledge Center



How can I replace a string of text in multiple files using Perl?

  1. From the desktop, press Alt+F2 to launch the Run Application window.
  2. Type: gnome-terminal then press Enter. This will launch a user terminal (similar to Windows command prompt).
  3. In the terminal window, type:cd ~then press Enter to change directory into your home directory.
  4. Next, we will create a test directory where you will be able to test the commands without impacting your other files. In the terminal, type:mkdir testthen press Enter.
  5. Now cd into your new directory.cd test
  6. Download the test file from the Attachments section (located at the bottom of this article) and save it to your test directory.
  7. View the contents of this file by typing:cat replace.txt
  8.  Before running the script, be certain that you are in your test directory. At the terminal, type:pwdthen press Enter. This prints the working directory which should be test. Also, type: ls to verify that replace.txt is in the test directory.
  9. Type the following into the terminal:perl -pi -e 's/red/truck/g' *.txt then press Enter.
  10. Now type:cat replace.txtAll occurences of the string: "red" have been replaced with the string: "truck".
  11. The replacement also works for more than one word. For example:perl -pi -e 's/green truck/boat/g' *.txtwill search for the string "green truck" and replace each instance with "boat".

Would you like to...


del.icio.us

Print this page Print this page

Email this page Email this page

Post a comment Post a comment

Subscribe me

Add to favoritesAdd to favorites

User Opinions (3 votes)

66% thumbs up 33% thumbs down

How would you rate this answer?

Helpful
Not helpful
Thank you for rating this answer.