繁体   English   中英

在双引号中使用双引号

[英]Using double quotes within double quotes

我有一个具有以下内容的file1.txt:

time="2016-04-25T17:43:11Z" level=info msg="SHA1 Fingerprint=9F:AD:D4:FD:22:24:20:A2:1E:0C:7F:D0:19:C5:80:42:66:56:AC:6F"

我希望文件看起来如下:

9F:AD:D4:FD:22:24:20:A2:1E:0C:7F:D0:19:C5:80:42:66:56:AC:6F  

实际上,我需要将命令作为字符串传递。 这就是为什么bash命令需要封装在带双引号的字符串中的原因。 但是,当我包括

 " grep -Po '(?<=Fingerprint=)[^"]*' "   

我没有得到想要的输出。 看来我需要正确地转义双引号。

要回答文字问题,可以在命令中使用反斜杠转义文字双引号。 但是,由于BashFAQ#50中给出的原因,这是非常糟糕的做法:

# Avoid this absent a very good reason
grep_cmd_str="grep -Po '(?<=Fingerprint=)[^\"]*'" 
eval "$grep_cmd_str" <file1.txt # eval is necessary, with all the issues that implies

in a variable is to use an array , not a scalar variable, to hold its arguments: 当您需要在变量中存储简单命令(无重定向或其他shell构造) ,更好的做法是使用数组而不是标量变量来保存其参数:

# Use this principally if you need to dynamically build up an argument list
grep_args=( grep -Po '(?<=Fingerprint=)[^"]*' )
"${grep_args[@]}" <file1.txt

如果您没有任何要求使用上述任何一种的约束,请考虑一个函数(只要重定向和shell构造经过硬编码,它就允许重定向和shell构造):

# Use this whenever possible, in preference to the above
grep_fp() { grep -Po '(?<=Fingerprint=)[^"]*' "$@"; }
grep_fp <file1.txt

- Not evaluating shell constructs, in this context, is a security feature: it protects you against malicious filenames or similar content in values which have been substituted into the value you're using as a command. -在这种情况下,不评估外壳结构是一项安全功能:它可以保护您免受恶意文件名或类似内容(已替换为您用作命令的值)中的内容的侵害。

- Note that arrays are not available in POSIX sh, which your question is also tagged for. -请注意,数组在POSIX sh中不可用,您的问题也被标记了。 也就是说,可以通过覆盖"$@" (大概在有限的范围内,例如函数,以保留其原始值)来获得类似的功能。

暂无
暂无

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

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