We use cookies to keep our site relevant and easy to use, your continued use of this site is consent that we may set several cookies (see our Privacy & Cookie Policy), click to always allow cookies from our site (and not see this notifcation on your next visit) or read more.Allow Cookies

EU legislation requires that all websites clearly specify if cookies are being used and their purpose, You can read more about how we use cookies (and which cookies we use) in our Privacy and Cookie Policy.

You will see this notification the first time you visit our website unless you accept cookies (in which case we'll set a cookie to remember thay you're happy for us to to set cookies!).

Linux Search and Replace

Sed can be a pain in the butt, so thanks to Shooter.net I’ve recently been changing files with perl using the following code:

perl -pi -e 's/search/replace/g' *.text

-p Assumes an input loop around the script. It reads each line of the file
and outputs it after processing
-i Activates in place editing of files
-e Indicates a single lines script
's/search/replace/g' is the script or command. In this case it's a search and replace regex
*.text the filename(s) to operate on

Extending this via some digging around I did for searching and replacing recursively through subdirectories, I found this piece of code:

find . -print | egrep "*\.html" | xargs perl -pi -e 's/this/that/g'

This is far cleaner than the old:

for each file in *.text
do
sed 's/search/replace/g' < $file >$file.tempfile
mv $file.tempfile $file
done

(The main limitation with sed being that it is unable to output directly to the file you are working on!)

This entry was posted on Friday, December 16th, 2005 at 4:32 pm and is filed under Linux. You can follow any responses to this entry through the RSS 2.0 feed.


Comments are closed.