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 ;-/


I am a Full stack Web Developer. I'm interested in Web Designing and passionate towards FOSS. I love Linux and like to promote it. A quick leaner, quick implementer, not away from errors, staying for software and knowledge freedom and doing programming in PHP, Mysql, Postgresql, Laravel, Angulajs and more..

Leave a Reply

Your email address will not be published. Required fields are marked *