Find and replace with sed in directory and sub directories

LinuxCommand LineSedReplace

Linux Problem Overview


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

Linux Solutions


Solution 1 - Linux

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

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

Solution 2 - Linux

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'

Solution 3 - Linux

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

Solution 4 - Linux

This worked for me:

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

Solution 5 - Linux

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

Solution 6 - Linux

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.

Solution 7 - Linux

Found a great program for this called ruplacer

https://github.com/dmerejkowsky/ruplacer

Usage

ruplacer before_text after_text # prints out list of things it will replace
ruplacer before_text after_text --go # executes the replacements

It also respects .gitignore so it won't mess up your .git or node_modules directories (find . by default will go into your .git directory and can corrupt it!!!)

Solution 8 - Linux

In linuxOS:

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

if "sed" not work try :

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhd.View Question on Stackoverflow
Solution 1 - Linuxjfg956View Answer on Stackoverflow
Solution 2 - LinuxJuliusView Answer on Stackoverflow
Solution 3 - Linuxpat-sView Answer on Stackoverflow
Solution 4 - LinuxblackdadView Answer on Stackoverflow
Solution 5 - LinuxrocLvView Answer on Stackoverflow
Solution 6 - LinuxSukrantView Answer on Stackoverflow
Solution 7 - LinuxColin DView Answer on Stackoverflow
Solution 8 - Linuxฉัตรชัย สิทธิวงค์View Answer on Stackoverflow