Home » Programming » How To “Find And Replace” Words In Multiple Files In a Folder

How To “Find And Replace” Words In Multiple Files In a Folder

This is a most tricky one for programmers. I got stuck with a situation. In a folder lot of php files start with

SED for Rescue

Find and Replace with SED

What is SED? SED is a stream editor or line editor in Linux or Unix. It reads input line by line (sequentially), applying the operation which has been specified via the command line (or a sed script), and then outputs the line. It was developed from 1973 to 1974 as a Unix utility by Lee E. McMahon of Bell Labs,[1] and is available today for most operating systems.

It isn’t really a true text editor or text processor. Sed is typically used for extracting part of a file using pattern matching or substituting multiple occurrences of a string within a file.

$ sed -i 's/foo/bar/g' /home/linux/people/programme.txt

This replaces all foo with bar.

Magic with SED and Our Find Command

$ find /home/dear/people -type f -exec sed -i 's/foo/bar/g' {} ;

There is a small shell script for this thing

 for fl in *.php; do
 mv $fl $fl.old
 sed 's/FINDSTRING/REPLACESTRING/g' $fl.old > $fl
 rm -f $fl.old

just replace the “*.php“, “FINDSTRING” and “REPLACESTRING” make it executable and you are set.

You can find a Documentation on http://www.brunolinux.com/02-The_Terminal/Find_and%20Replace_with_Sed.html

and Find command documentation on http://www.brunolinux.com/02-The_Terminal/The_Find_Command.html

For the lovers of perl
# perl -e "s/old_string/new_string/g;" -pi.save $(find DirectoryName -type f)
But it leaves “traces”, e.g it backs up the old file with a .save extension . . . so is not really effective when Sue comes around ;-/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.