【问题标题】:Replace " by \" inside a string [duplicate]将字符串中的“替换为\”[重复]
【发布时间】:2017-05-01 04:42:06
【问题描述】:

如何使用 bash 将字符串中的 " 替换为 \"

例如:

一个 txt 文件包含如下文本:

Banana "hallo" Apple "hey"

这必须转换成:

Banana \"hallo\" Apple \"hey\"

我试过了

a=$(cat test.txt)
b=${a//\"/\"}}

但这没有用。

它是如何工作的?

【问题讨论】:

  • 你能告诉我们你到目前为止做了什么吗?
  • 例如a=$(cat test.txt) 和 b=${a//\"/\"}} 这当然行不通
  • 您的问题对您的要求有点模糊。通常,您可以使用sedawk 来解决此类问题。还有其他可能性。
  • 问题是," 是一个特殊字符。所以 Julien Lopez 提出的解决方案是不可能的。
  • @AnneK。你实际上非常接近。但是,如果您想要文字 ` or "`,则需要对 ` and "` 进行转义

标签: string bash replace


【解决方案1】:

使用[ parameter expansion ]

string='Banana "hallo" Apple "hey"'
echo "$string"
Banana "hallo" Apple "hey"
string=${string//\"/\\\"} # Note both '\' need '"' need to be escaped.
echo "$string"
Banana \"hallo\" Apple \"hey\"

小解释

${var/pattern/replacement}

replacement 替换var 中出现的pattern 一个

${var//pattern/replacement}

replacement替换var中出现的pattern所有

如果模式或替换包含像"/这样在shell中具有特殊含义的字符,则需要对其进行转义以让shell将它们视为文字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-28
    • 2021-05-13
    • 2011-10-10
    • 1970-01-01
    • 2021-06-17
    • 2012-10-05
    相关资源
    最近更新 更多