string 在我当前目录下的所有文件中用另一个字符串替换一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7450324/
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
Replace a string with another string in all files below my current dir
提问by KRB
How do I replace every occurrence of a string with another string below my current directory?
如何用当前目录下的另一个字符串替换每个出现的字符串?
Example:I want to replace every occurrence of www.fubar.com
with www.fubar.ftw.com
in every file under my current directory.
示例:我想替换当前目录下每个文件中所有出现的www.fubar.com
with www.fubar.ftw.com
。
From research so far I have come up with
从研究到目前为止,我想出了
sed -i 's/www.fubar.com/www.fubar.ftw.com/g' *.php
回答by martin clayton
You're on the right track, use find
to locate the files, then sed
to edit them, for example:
您在正确的轨道上,用于find
定位文件,然后sed
编辑它们,例如:
find . -name '*.php' -exec sed -i -e 's/www.fubar.com/www.fubar.ftw.com/g' {} \;
Notes
笔记
- The
.
means current directory - i.e. in this case, search in and below the current directory. - For some versions of
sed
you need to specify an extension for the-i
option, which is used for backup files. - The
-exec
option is followed by the command to be applied to the files found, and is terminated by a semicolon, which must be escaped, otherwise the shell consumes it before it is passed to find.
- 该
.
方法的当前目录-即,在这种情况下,在搜索和下面的当前目录。 - 对于某些版本,
sed
您需要为该-i
选项指定一个扩展名,用于备份文件。 - 该
-exec
选项后跟要应用于找到的文件的命令,并以分号终止,必须对其进行转义,否则 shell 在将其传递给 find 之前将其消耗掉。
回答by johnny
Solution using find, args and sed:
使用 find、args 和 sed 的解决方案:
find . -name '*.php' -print0 | xargs -0 sed -i 's/www.fubar.com/www.fubar.ftw.com/g'
回答by rubo77
If there are no subfolders, a simpler to remember way is
如果没有子文件夹,一个更简单的记忆方法是
replace "www.fubar.com" "www.fubar.ftw.com" -- *
where * can also be a list of files
其中 * 也可以是文件列表
from the manual:
从手册:
Invoke replace in one of the following ways:
shell> replace from to [from to] ... -- file_name [file_name] ... shell> replace from to [from to] ... < file_name
通过以下方式之一调用替换:
shell> replace from to [from to] ... -- file_name [file_name] ... shell> replace from to [from to] ... < file_name
If you have hidden files with a dot you can add those to *
with
如果您已经隐藏以点文件,您可以添加到那些*
与
shopt -s dotglob
If you only have one depth of subfoldersyou can use */*
instead of *
如果您只有一个深度的子文件夹,则可以使用*/*
而不是*
replace "www.fubar.com" "www.fubar.ftw.com" -- */*
回答by Seweryn Niemiec
When using ZSHas your shell you can do:
使用ZSH作为 shell 时,您可以执行以下操作:
sed -i 's/www.fubar.com/www.fubar.ftw.com/g' **/*.php
回答by bash-o-logist
A pure bash solution
一个纯粹的 bash 解决方案
#!/bin/bash
shopt -s nullglob
for file in *.php
do
while read -r line
do
echo "${line/www.fubar.com/www.fubar.ftw.com}"
done < "$file" > tempo && mv tempo "$file"
done