Linux 在目录和子目录中查找并替换为 sed

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6758963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:09:16  来源:igfitidea点击:

Find and replace with sed in directory and sub directories

linuxcommand-linesedreplace

提问by hd.

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

我运行此命令以在我的站点根目录中的所有文件中查找和替换所有出现的 'apple' 为 'orange':

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 ./:

以下是一些输出行find ./

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

采纳答案by jfg956

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

您的 find 应该是这样的,以避免将目录名称发送到 sed:

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

回答by blackdad

This worked for me:

这对我有用:

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

回答by Sukrant

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.

请参阅此页面

回答by Julius

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

对于更大的 s&r 任务,使用 grep 和 xargs 更好更快,例如;

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

回答by ??????? ?????????

In linuxOS:

在 linux 操作系统中:

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

if "sed" not work try :

如果“sed”不起作用,请尝试:

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

回答by rocLv

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

回答by pat-s

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

因为也有 macOS 的人在读这个(就像我一样),下面的代码对我有用(在 10.14 上)

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

All other answers using -iand -edo not work on macOS.

所有其他答案都使用-i并且-e不适用于 macOS。

Source

来源