[prog] using sed on multiple files

Douglas Hunter dug at plusthree.com
Sat Jul 9 03:20:48 EST 2005


Nicki Handy wrote:
> Hi, I want to use the sed command on multiple files so that I can 
> replace a piece of text in each of the files. The problem is the output- 
> I can run the command fine on the whole directory but I don't want to 
> have to specify the file to output, I just want it to change the file 
> it's on.
> 

I typically reach for Perl for this task.  It has a command line flag 
for in-place editing of files.  I apologize for my sed ignorance, but 
maybe the Perl example can help.

> For example, this works.....
> machine# find ./ -type f -exec sed -e 's/051201/081201' {} \;
> 
> But I need it to permanently make the change not just spit the output to 
> STDOUT
> I can add a w but it needs to be dymanic
> 
> # find ./ -type f -exec sed -e 's/051201/081201/w' {} \;
> 
> Anyone know how to accomplish this?

To do a search and replace of every file in a directory, doing an 
in-place edit of that file, I would use:

perl -pi -e 's/051201/081201/;' *

or

perl -pi.bak -e 's/051201/081201/;' *

if I wanted backups of the original files.

or

perl -pi.bak -e 's/051201/081201/;' *.txt

if I only wanted to perform the substitution in files with a .txt extension.

There is a nice discussion of this here: http://hacks.oreilly.com/pub/h/73

-- Douglas Hunter


More information about the Programming mailing list