- From the desktop, launch a new terminal session by selecting: Applications > Accessories > Terminal.
- At the prompt (the blinking cursor), type:
cd ~
then press Enter. You will now be in you home directory inside the terminal. - 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 test
then press Enter. - Navigate into your new directory:
cd test
then press Enter. - Copy the following code and paste it into your terminal using either: Ctrl+Shift+V or right-click > Paste
touch replace.txt ; echo 'test
then press Enter.
blue
red
white blue
pink red
red orange yellow yellow
purple orange
green red pink
green red' > replace.txt - To view the contents of this file, type:
cat replace.txt
- Type the following into the terminal:
perl -pi -e 's/red/truck/g' replace.txt
then press Enter. - Now type:
cat replace.txt
All occurences of the string: "red" have been replaced with the string: "truck". - 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
02 June 2010
Using Perl to replace strings in multiple text files
Labels:
perl,
shell programming
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment