02 June 2010

Using Perl to replace strings in multiple text files

  1. From the desktop, launch a new terminal session by selecting: Applications > Accessories > Terminal.
  2. At the prompt (the blinking cursor), type: cd ~ then press Enter. You will now be in you home directory inside the terminal.
  3. 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.
  4. Navigate into your new directory: cd test then press Enter.
  5. Copy the following code and paste it into your terminal using either: Ctrl+Shift+V or right-click > Paste touch replace.txt ; echo 'test
    blue
    red
    white blue
    pink red
    red orange yellow yellow
    purple orange
    green red pink
    green red' > replace.txt
    then press Enter.
  6. To view the contents of this file, type:cat replace.txt
  7. Type the following into the terminal: perl -pi -e 's/red/truck/g' replace.txt then press Enter.
  8. Now type:cat replace.txt All occurences of the string: "red" have been replaced with the string: "truck".
  9. The replacement also works for more than one word. For example:perl -pi -e 's/green truck/boat/g' replace.txt will search for the string "green truck" and replace each instance with "boat". To adapt this code to replace a string in multiple text files, simply change the target file from replace.txt to *.txt:perl -pi -e 's/green truck/boat/g' *.txt

No comments: