【问题标题】:Handling text containing both quote types处理包含两种引用类型的文本
【发布时间】:2015-09-12 00:29:08
【问题描述】:

我想在 Linux 中将以下文本附加到文件中:

echo He said "I can't append this" >> file.txt
cat file.txt
He said I can't append this

closest solution I've found 不起作用。如何在附加的字符串中包含两组引号?

【问题讨论】:

  • echo "He said \"I can't append this\"" => He said "I can't append this"

标签: bash


【解决方案1】:

最好使用here-doc 避免疯狂转义:

cat<<'EOF' > file.txt
He said "I can't append this"
EOF

【讨论】:

    【解决方案2】:

    要避免使用cat,可以使用printf

    printf 'He said "%s"\n' "I can't append this" >> file.txt
    

    【讨论】:

      【解决方案3】:

      你可以像这样连接字符串:

      echo He said '"'"I can't append this"'"'
      

      或:

      echo 'He said "I can'"'"'t append this"'
      

      但最好的选择可能是使用\ 转义字符:

      echo 'He said "I can\'t append this"' # note: this is wrong - see comment
      

      编辑: 正如@gniourf_gniourf 的评论中所述,先前使用转义字符的解决方案是错误的。正确的版本是

      echo "He said \"I can't append this\""
      

      【讨论】:

      • 您的最后一个解决方案(作为最佳选择)不起作用:由于字符串在单引号内,因此反斜杠不会充当转义字符,并且以下单引号会关闭第一个一。
      • 另外,你不能在单引号内转义单引号。
      猜你喜欢
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      相关资源
      最近更新 更多