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
Find and replace with sed in directory and sub directories
提问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
回答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 -i
and -e
do not work on macOS.
所有其他答案都使用-i
并且-e
不适用于 macOS。