bash - 以编程方式将参数提供给 sed

标签 bash shell sed

假设我有一个 bash 脚本,它首先解析参数/文件。结果,脚本生成以下字符串:

args="-e 's/\\\$foo\\b/bar/gi' -e 's/\\\$baz\\b/qux/gi'"

现在我想输入结果字符串 (-e 's/\$foo\b/bar/gi' -e 's/\$baz\b/qux/gi') sed 以执行搜索并替换例如以下文件:

Hello $foo, hello $baz

如果使用 sed -e 's/\$foo\b/bar/gi' -e 's/\$baz\b/qux/gi',它返回:

Hello bar, hello qux

如果有人打电话:

sed $args

它给出了一个错误:

sed: -e expression #1, char 1: unknown command: `''

如何以编程方式将一系列参数提供给 sed

最佳答案

避免所有疯狂的转义并将 args 变量声明为 shell 数组:

args=(-e 's/\$foo\b/bar/gi' -e 's/\$baz\b/qux/gi')

然后在 sed 中使用它作为:

s='Hello $foo, hello $baz'
echo "$s" | sed "${args[@]}"
Hello bar, hello qux

关于bash - 以编程方式将参数提供给 sed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34663919/

相关文章:

bash - 快速帮助 bash 脚本删除大文件的行

linux - 如何向 bash 脚本添加线程?

c++ - 应用程序中的嵌入式控制台工具功能

bash - 使用 shell 解析 HTML

bash - 删除 Bash 中的位置参数?

regex - sed 插入行命令 OSX

bash - Linux/庆典 : remove text between two chars

windows - RStudio 在 Windows 10 上未检测到 .gitconfig 文件

bash - 执行时保留颜色代码

bash - shell bash - 返回码