274
votes

I run this command to find and replace all occurrences of 'apple' with 'orange' in all files in root of my site:

find ./ -exec sed -i 's/apple/orange/g' {} \;

But it doesn't go through sub directories.

What is wrong with this command?

Here are some lines of output of find ./:

./index.php
./header.php
./fpd
./fpd/font
./fpd/font/desktop.ini
./fpd/font/courier.php
./fpd/font/symbol.php
7
could you run find ./ and post some sample output? And the directory strucuture please. edit: thanks!Jacob
Hm your find is correct, works for me with subdirs.Jacob
How do you know it does not process subdirectories?carlpett
because it gives these errors: sed: couldn't edit ./fpd: not a regular file sed: couldn't edit ./fpd/font: not a regular file sed: couldn't edit ./fpd/font/makefont: not a regulahd.
oh... i grep for apple and nothing found.they all were replaced. ;) thank you . you opened my eyes !!!hd.

7 Answers

476
votes

Your find should look like that to avoid sending directory names to sed:

find ./ -type f -exec sed -i -e 's/apple/orange/g' {} \;
109
votes

For larger s&r tasks it's better and faster to use grep and xargs, so, for example;

grep -rl 'apples' /dir_to_search_under | xargs sed -i 's/apples/oranges/g'
5
votes

This worked for me:

find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;
4
votes

Since there are also macOS folks reading this one (as I did), the following code worked for me (on 10.14)

egrep -rl '<pattern>' <dir> | xargs -I@ sed -i '' 's/<arg1>/<arg2>/g' @

All other answers using -i and -e do not work on macOS.

Source

3
votes
grep -e apple your_site_root/**/*.* -s -l | xargs sed -i "" "s|apple|orage|"
0
votes

I think we can do this with one line simple command

for i in `grep -rl eth0 . 2> /dev/null`; do sed -i ‘s/eth0/eth1/’ $i; done

Refer to this page.

-8
votes

In linuxOS:

sed -i 's/textSerch/textReplace/g' namefile

if "sed" not work try :

perl -i -pe 's/textSerch/textReplace/g' namefile