如何在bash中用两个单引号替换单引号

Jam*_*ish 0 bash sed

我正在尝试使用 sed 用双引号替换字符串中的单引号。

我试过这样回声这是美好的一天 | sed "s/'/\"/g" 但该字符串没有找到匹配项,也没有给出任何结果。

我在 Windows 的 Ubuntu 上使用 Bash

我究竟做错了什么?

Fre*_*red 7

扩展可以非常简单地为您提供您想要的东西:

original="it's a lovely day"
modified=${original//\'/\"}
echo "$modified"
Run Code Online (Sandbox Code Playgroud)

除了简单之外,这个扩展没有使用外部命令(只有shell特性),所以性能开销比启动一个单独的进程要低得多。

稍微分解一下语法:

  • ${original...}意味着我们正在扩展original变量
  • // 意思是“搜索所有出现的”
  • \' 是转义的单引号(要搜索的文本)
  • 孤独的/意思是“替换”
  • \" 是一个转义的双引号(要替换的文本)

另一种有趣的方式来做到这一点:

repl()
{
  local IFS="$2$1"
  set -- $3
  echo "$*"
}

repl \'  \"  "it's a lovely day"
repl "'" '"' "it's a lovely day" # Quoted rather than escaped
Run Code Online (Sandbox Code Playgroud)

可以以子外壳为代价使 POSIX 兼容(请参阅下面的评论):

repl()
(
  IFS="$2$1"
  set -- $3
  echo "$*"
)

(repl \'  \"  "it's a lovely day")
(repl "'" '"' "it's a lovely day") # Quoted rather than escaped
Run Code Online (Sandbox Code Playgroud)

子shell 是通过将语句括在括号中来创建的。不这样做会改变 IFS 的值(它不像第一个版本那样被声明为“本地”),你很可能想要避免这种情况。