Find and Replace Specific Occurrence across Multiple Files

Find and Replace Specific Occurrence across Multiple Files

Sometimes you might need to find and replace specific occurrence  across multiple files. In linux system you can do your task with just a single command line.  Imagine you have a large and multiple files ( txt, php, html, anything ) and you want to replace all the words , no doubt it’s very time consuming . With ‘sed’ command you can complete your task pretty easily.

Below is example, if you like to change all the php files in a specific directory

t looks a bit complicated but its quite simple. There are three components to the command:

find . -name “*.php” -print – Find all files (recursively) which has “.php” in the file and print them out. This will give you output like this:

xargs– This command is used when you want to pass a lot of arguments to one command. xargs will combine the single line output of find and run commands with multiple
arguments, multiple times if necessary to avoid the max chars per line limit. In this case we combine xargs with sed
sed -i ‘s/foo/bar/g’ – aka Stream Editor is a tool which should be in every sys admin’s toolkit.  In this case every occurence of “foor” is replaced by “bar” in all the files found using the “find” command. Sed simply parses input and applies certain text transformations to it. There’s a lot to say about sed, you can find more at this tutorial.

This pretty much covers the core of the find & replace command. You could also open up a particular folder in an IDE and use it’s find and replace feature. But find + sed is quite fast and powerful.

468 ad

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">