Find and replace with sed in directory and sub dir

2019-01-03 19:47发布

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?

Edited: here is some lines of output of find ./ command:

./index.php
./header.php
./fpd
./fpd/font
./fpd/font/desktop.ini
./fpd/font/courier.php
./fpd/font/symbol.php

6条回答
男人必须洒脱
2楼-- · 2019-01-03 20:14

In linuxOS:

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

if "sed" not work try :

perl -i -pe 's/textSerch/textReplace/g' namefile
查看更多
趁早两清
3楼-- · 2019-01-03 20:15

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'
查看更多
祖国的老花朵
4楼-- · 2019-01-03 20:19

This worked for me:

find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;
查看更多
Juvenile、少年°
5楼-- · 2019-01-03 20:24

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

find ./ -type f -exec sed -i -e 's/apple/orange/g' {} \;
查看更多
【Aperson】
6楼-- · 2019-01-03 20:25
grep -e apple your_site_root/**/*.* -s -l | xargs sed -i "" "s|apple|orage|"
查看更多
戒情不戒烟
7楼-- · 2019-01-03 20:28

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.

查看更多
登录 后发表回答