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.


What I'm Doing...

  • Not really looked properly at EC2 in a long time, but all @lgladdy 's tweets about it are pushing me in that direction again, any good tips? 13 mins ago
  • Android why can't I create a repition of a calendar event every other week? I can do weekly, every xth of the month but not every other! 11 hrs ago
  • Get a private beta invite for Connect.Me. It's your reputation card for the social web http://t.co/ZWV66HMM 12 hrs ago
  • Waiting for a callback from the doctor, why can't they tweet me or do a Skype diagnosis? 1 day ago
  • RT @CatherineQ: Congrats team in white shiny pants that won. Commiserations to team in white shiny pants that didn't win. #Superbowl < ;) 1 day ago
  • More updates...
@Keiron