bash 在命令替换中转义 AWK 中的反斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16801731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:31:57  来源:igfitidea点击:

Escaping backslash in AWK in command substituion

bashawkbackslashcommand-substitution

提问by Bill

I am trying to escape backslash in AWK. This is a sample of what I am trying to do.

我试图在 AWK 中逃避反斜杠。这是我正在尝试做的一个示例。

Say, I have a variable

说,我有一个变量

$echo $a
hi

The following works

以下作品

$echo $a | awk '{printf("\\"%s\"",)'}
\"hi"

But, when I am trying to save the output of the same command to a variable using command substitution, I get the following error:

但是,当我尝试使用命令替换将同一命令的输出保存到变量时,出现以下错误:

$ q=`echo $a | awk '{printf("\\"%s\"",)'}`
awk: {printf("\"%s\"",)}
awk:               ^ backslash not last character on line

I am unable to understand why command substitution is breaking the AWK. Thanks a lot for your help.

我无法理解为什么命令替换会破坏 AWK。非常感谢你的帮助。

采纳答案by jaypal singh

Try this:

尝试这个:

q=$(echo $a | awk '{printf("\\"%s\"",)}')

Test:

测试:

$ a=hi
$ echo $a
hi
$ q=$(echo $a | awk '{printf("\\"%s\"",)}')
$ echo $q
\"hi"

Update:

更新:

It will, it just gets a littler messier.

它会的,它只会变得更混乱。

q=`echo $a | awk '{printf("\\\"%s\"",)}'`

Test:

测试:

$ b=hello
$ echo $b
hello
$ t=`echo $b | awk '{printf("\\\"%s\"",)}'`
$ echo $t
\"hello"

Reference

参考

回答by Uwe

Quoting inside backquoted commands is somewhat complicated, mainy because the same token is used to start and to end a backquoted command. As a consequence, to nest backquoted commands, the backquotes of the inner one have to be escaped using backslashes. Furthermore, backslashes can be used to quote other backslashes and dollar signs (the latter are in fact redundant). If the backquoted command is contained within double quotes, a backslash can also be used to quote a double quote. All these backslashes are removed when the shell reads the backquoted command. All other backslashes are left intact.

在反引号命令中引用有点复杂,主要是因为相同的标记用于开始和结束反引号命令。因此,要嵌套反引号命令,必须使用反斜杠转义内部命令的反引号。此外,反斜杠可用于引用其他反斜杠和美元符号(后者实际上是多余的)。如果反引号命令包含在双引号内,则反斜杠也可用于引用双引号。当 shell 读取反引号命令时,所有这些反斜杠都会被删除。所有其他反斜杠保持不变。

The new $(...)avoids these troubles.

新的$(...)避免了这些麻烦。

回答by Chris Seymour

Don't get into bad habits with backticks, quoting and parsing shell variables to awkThe correct way to do this is:

不要养成使用反引号、引用和解析 shell 变量的坏习惯awk正确的方法是:

$ shell_var="hi"

$ awk -v awk_var="$shell_var" -v c='\' 'BEGIN{printf "%s%s\n",c,awk_var}'
\hi

$ res=$(awk -v awk_var="$shell_var" -v c='\' 'BEGIN{printf "%s%s\n",c,awk_var}')

$ echo "$res"
\hi