- 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 testthen press Enter. - Navigate into your new directory:
cd testthen 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 'testthen 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.txtthen press Enter. - Now type:
cat replace.txtAll 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.txtwill 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
Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts
02 June 2010
Using Perl to replace strings in multiple text files
Subscribe to:
Posts (Atom)