Sed find and replace in folder

Saturday, 23 February 2008

Here's a handy one-liner to help you replace strings globally throughout all the files in a specified folder. This procedure is also called mass find and replace, or global replace.

You can even use it on windows if you're willing to spent a few minutes installing cygwin , a windows port of the gnu/linux most used utilities (including the bash shell and even X11)

The code below will replace every occurence of 'ugly' with 'beautiful'. 

Linux example: 

find /home/bruno/old-friends -type f -exec sed -i 's/ugly/beautiful/g' {} ;

 

Cygwin example (you have to use unix-style paths):

find /cygdrive/c/xampp/joomla/ -type f -exec sed -i 's/ugly/beautiful/g' {} ;

 

 /cygdrive/c/ stands for the root of your C windows drive letter

Also note that Cygwin requires you to use the forward slash delimiter instead of the windows backslash delimiter. The bash shell allows TAB completion for paths, just type the first few letters and hit TAB to auto-complete the path. 

If you want to filter, let's say,  php files, you can add -name '*.php' to command-line arguments, just after the search path.

find /cygdrive/c/xampp/joomla/ -type f -name '*.php' -exec sed -i 's/ugly/beautiful/g' {} ;


Give us some social love (it really works now)!

Reddit! Del.icio.us! StumbleUpon! Yahoo! Swik!



Comments (2)
RSS comments
1. Delimiters05-05-2008 19:16

If you're having trouble trying to replace strings that contain slashes or backslashes, you can always use pipe '|' as a string delimiter 
find /cygdrive/c/xampp/joomla/ -type f -name '*.php' -exec sed -i 's|yes\/no|ok\/cancel|g' {} \;

2. Software Engineer28-05-2008 22:57

Hi, 
 
I appreciated the sample mass replace line. 
 
On my linux (Gentoo), I had to escape the semicolon to get it to work: 
find . -type f -name "*.sh" -exec sed -i 's/projects/sandbox/g' '{}' \;  
 
It then worked great! 
 
Thanks again, 
 
j

Write Comment
  • Please keep the topic of messages relevant to the subject of the article.
  • Please don't use comments to plug your web site. Links are rel='nofollow'-ed
  • Please refresh the page if you're having trouble with the security image code
Name:
E-mail
Homepage
Title:
Comment:

:) :grin ;) 8) :p
:roll :eek :upset :zzz :sigh
:? :cry :( :x
Code:* Code

Last Updated ( Thursday, 24 July 2008 )
 
Post and Bid on Joomla/PHP projects! Join EUFreelance.com for free!

Newsletter

Subscribe to TeachMeJoomla's newsletter
Name:
Email:


Auto tags

sed search and replace

sed find and replace

sed replace

sed find

sed search replace

sed find replace

find sed

linux sed replace

find and replace sed

sed global replace

find exec sed

sed replace line

find and replace with sed

search and replace the string inside a folder in unix

linux mass replace