使用一个 sed 命令进行多次替换 [英] Multiple replacements with one sed command
问题描述
我想知道如何在 Mac OSX
中使用单个 sed
语句进行多次查找/替换.我可以在 Ubuntu
中执行此操作,但由于 OSX
的 BSD
性质,必须稍微更改命令.
I'm wondering how I can do a multiple find/replace using a single sed
statment in Mac OSX
. I'm able to do this in Ubuntu
but because of the BSD
nature of OSX
, the command must be slightly altered.
所以,给定一个带有字符串的文件:
So, given a file with the string:
"Red Blue Red Blue Black Blue Red Blue Red"
我想运行一个产生输出的 sed 语句:
I want to run a sed statement that results in the output:
"Green Yellow Green Yellow Black Yellow Green Yellow Green"
我的两个带有限定 find
的 sed 语句
My two sed statements with a qualifying find
color1="Green"
color2="Yellow"
find . -type f -exec sed -i '' s/Red/$color1/g {} ;
find . -type f -exec sed -i '' s/Blue/$color2/g {} ;
我尝试了几种分号和斜线的组合,并查看了 Apple 的 sed 开发手册页 但由于缺少示例,我无法将它们拼凑在一起.
I've tried several combinations of semicolons and slashes, and looked at Apple's Dev man page for sed but with a lack of examples, I couldn't piece it together.
推荐答案
Apple 的手册页说可以使用 -e 或 -f 选项指定多个命令. 所以我会说>
Apple's man page says Multiple commands may be specified by using the -e or -f options. So I'd say
find . -type f -exec sed -i '' -e s/Red/$color1/g -e s/Blue/$color2/g {} ;
这当然适用于 Linux 和其他 Unices.
This certainly works in Linux and other Unices.
这篇关于使用一个 sed 命令进行多次替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!