简体   繁体   English

如何将 sed arguments 存储在变量中以在 BASH 中进行参数替换

[英]How to store sed arguments in variable for parameter substitution in BASH

I need to store some sed expressions in a variable and substitute it in the sed command.我需要将一些 sed 表达式存储在变量中,并在 sed 命令中替换它。

myArgs="-e 's/foo/bar/' -e 's/foo2/bar2/'"

So far these are not working:到目前为止,这些都不起作用:

echo "foo" | sed ${myArgs} 
# sed: -e expression #1, char 1: unknown command: `''

echo "foo" | sed  $(echo ${myArgs})
# sed: -e expression #1, char 1: unknown command: `''

echo ${myArgs}
's/foo/bar/' -e 's/foo2/bar2/'
# 1st -e missing

Parameter expansion interprets the first -e argument in the variable.参数扩展解释变量中的第一个 -e 参数。

-e may be interpreted as a test for exist, or argument to echo. -e 可以解释为存在的测试,或回显的参数。

How can I prevent this and use it literally for the sed command?如何防止这种情况并将其用于 sed 命令?

To clarify, this is just a simplified version of a command that will contain a large number of sed expressions with characters that require escaping in the regex, and I would rather keep the expressions quoted as-is, and dump all the sed expressions into the sed command as a single variable.澄清一下,这只是一个命令的简化版本,它将包含大量 sed 表达式,其中的字符需要正则表达式中的 escaping,我宁愿保持原样引用的表达式,并将所有 Z177544AAA7590AF6F324EZF8 表达式转储到表达式中sed 命令作为单个变量。

If that's not possible, I'll use a different method such as the current answers below, however it seems there should be some built in bash method to not pre-expand the variable, and instead just interpret it as a string, before it's used in the final sed command.如果这不可能,我将使用不同的方法,例如下面的当前答案,但是似乎应该有一些内置的 bash 方法不预先扩展变量,而是在使用之前将其解释为字符串在最后的 sed 命令中。

The actual arguments I'm using will look something like this:我使用的实际 arguments 看起来像这样:

-e 's/^>chr1.*/>NC_032089.1_chr1/' -e 's/^>chr2.*/>NC_032090.1_chr2/'

With unknown strings带有未知字符串

Don't use a string, use an array:不要使用字符串,使用数组:

myArgs=("-e" "s/foo/bar/" "-e" "s/foo2/bar2/")
sed "${myArgs[@]}" <<< "foo"

Since we know the input, and the sed code is safe enough, it's OK to use eval here:由于我们知道输入,并且sed代码足够安全,所以在这里使用eval是可以的:

echo foo | eval sed $myArgs

Output: Output:

bar

Related Q. about things to be wary of: Why should eval be avoided in Bash, and what should I use instead?相关Q.关于注意事项: Bash中为什么要避免eval,应该用什么代替?

Mo Budlong 's Sunworld column Command line psychology 101 is the most helpful thing I've seen for understanding command line parsing. Mo Budlong的 Sunworld 专栏命令行心理学 101是我见过的对理解命令行解析最有帮助的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM