【问题标题】:double backslashes of sed single-quoted command inside command substitutions get translated to a single backslash命令替换中的 sed 单引号命令的双反斜杠被转换为单个反斜杠
【发布时间】:2016-06-13 22:06:07
【问题描述】:
printf '%s' 'abc' | sed 's/./\\&/g'                        #1, \a\b\c
printf '%s' "`printf '%s' 'abc' | sed 's/./\\&/g'`"        #2, &&&

第二个反引号内的表达式返回\a\b\c,我们有printf '%s' "\a\b\c",所以它应该打印\a\b\c。 我的问题是:为什么第二个脚本打印 &&&

注意: 我可以通过在每个反斜杠前面加上另一个反斜杠来获得第二个脚本工作(打印\a\b\c),但我不知道为什么需要它。

一个相关问题: why does this single quoted string get interpreted when it's inside of a command substitution

【问题讨论】:

  • printf '%s' "$(printf '%s' 'abc' | sed 's/./\\&/g')" 工作正常
  • @anubhava 哇,真的。所以我猜背杆有一些奇怪的副作用。
  • 是的,反引号很糟糕,真的没有理由使用它们。在此处查看有关您的问题的更多信息mywiki.wooledge.org/BashFAQ/082
  • 是的,现在不鼓励使用反引号
  • @123 感谢您的链接,非常有用。

标签: shell sed sh backticks command-substitution


【解决方案1】:

这是一个很好的例子来说明反引号和$(cmd) 命令替换之间的区别。

当使用旧式反引号替换形式时,反斜杠 保留其字面意义,除非后面跟“$”、“`”或“\”。 前面没有反斜杠的第一个反引号会终止命令 替代。使用“$(COMMAND)”形式时,所有字符之间 括号构成命令;没有人受到特殊对待。

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html

看看你的例子,我用echo而不是printf

kent$  echo 'abc' | sed 's/./\\&/g'
\a\b\c

kent$  echo -E "`echo 'abc' | sed 's/./\\&/g'`"
&&&

kent$  echo -E "$(echo 'abc' | sed 's/./\\&/g')"                    
\a\b\c

您可以看到,反引号命令替换使您的\\ 成为单个\,因此与后面的& 一起成为\&(文字&

请注意,我使用echo -E 是为了禁用对反斜杠转义的解释,以便可以打印出\a\b\c

【讨论】:

    【解决方案2】:

    因为在第二行:

    你是说:

    printf '%s' 'abc' -> 'abc'
    

    然后替换:

    'abc'| sed 's/./\\&g' -> &&&
    
    The s mean substitute
    . mean one character
    \\& by a char &
    g mean multiple occurrence on the line
    

    所以你是说:

    将 abc 中的每个字符替换为 & 在同一行上多次

    \\\&的解释:

    Two backslashes become a single backslash in the shell which then in sed escapes the forward slash which is the middle delimiter.
    
    \\& -> \& (which makes the forward & a regular character instead of a delimiter)
    
    Three of them: The first two become one in the shell which then escape the third one in sed
    \\\& -> \\&
    

    终于!不要忘记您的命令在反引号下:

    您必须“两次”转义它的原因是因为您在一个解释双引号字符串一次的环境(例如 shell 脚本)中输入此命令。然后它被子shell再次解释。

    发件人:

    Why does sed require 3 backslashes for a regular backslash?

    【讨论】:

    • 双反斜杠是单引号的,所以我认为没有必要像我的问题中的第一种情况那样进一步转义它。
    • 感谢您的回答,原因是反引号。
    猜你喜欢
    • 2022-01-27
    • 2013-04-15
    • 2012-06-16
    • 2010-09-11
    • 1970-01-01
    • 2017-07-25
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多