我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
当前回答
对我来说最简单的方法是
grep -rl oldtext . | xargs sed -i 's/oldtext/newtext/g'
其他回答
我只使用上衣:
find . -name '*.[c|cc|cp|cpp|m|mm|h]' -print0 | xargs -0 tops -verbose replace "verify_noerr(<b args>)" with "__Verify_noErr(<args>)" \
replace "check(<b args>)" with "__Check(<args>)"
使用grep和sed的组合
for pp in $(grep -Rl looking_for_string)
do
sed -i 's/looking_for_string/something_other/g' "${pp}"
done
有点陈旧,但这在OS X上有效。
有几个诡计:
•仅编辑当前目录下扩展名为.sls的文件
• . 必须转义,以确保sed不会将它们求值为“任何字符”
•,用作sed分隔符,而不是通常的分隔符/
还要注意,这是为了编辑Jinja模板以在导入路径中传递变量(但这是离题的)。
首先,验证sed命令是否符合您的要求(这只会将更改打印到stdout,不会更改文件):
for file in $(find . -name *.sls -type f); do echo -e "\n$file: "; sed 's,foo\.bar,foo/bar/\"+baz+\"/,g' $file; done
准备好进行更改后,根据需要编辑sed命令:
for file in $(find . -name *.sls -type f); do echo -e "\n$file: "; sed -i '' 's,foo\.bar,foo/bar/\"+baz+\"/,g' $file; done
请注意sed命令中的-i“”,我不想创建原始文件的备份(如OS X上使用sed进行的就地编辑或本页中Robert Lujo的评论所述)。
快乐的色丁们!
要替换git存储库中的所有事件,可以使用:
git ls-files -z | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'
查看本地git repo中的列表文件?获取列出存储库中所有文件的其他选项。-z选项告诉git用零字节分隔文件名,这确保xargs(使用选项-0)可以分隔文件名(即使它们包含空格或其他内容)。
grep-lr'submainA.example.com'|读取文件时;do sed-i“s/submainA.example.com/submainB.example.com/g”“$file”;完成
我想大多数人都不知道他们可以将某些内容导入“while read file”,这样可以避免那些讨厌的-print0参数,同时在文件名中预设空格。
在sed之前进一步添加一个echo,可以让您在实际执行之前查看哪些文件将发生更改。