如何用撇号替换字符串中的双引号(不是指定它是字符串的外部双引号)

How to replace double quotes within a string with apostrophe (not the outer double quotes specifying it's a string)

我在 Linux 中有管道分隔的 .txt 文件,其中包含双引号内的字符串。

一些字符串将使用双引号而不是撇号。

例如我是一个字符串。

这将在管道中的文件中表示为“我是一个字符串”

我需要将“我是一个字符串”替换为“我是一个字符串”。

如何使用 sed 或使用 Python/Jupyter 来做到这一点?

例子

"String"|"I"m not a valid string"|"I'm a valid string"

根据数据要求,我不需要担心以下问题:

  1. 双引号内的竖线,例如“Str|Srt”|“Str”
  2. 双引号和单引号的混合 e.t。 “Str'|'Str”

使用sed时应该对"和'进行转义。sed命令的语法是: “s/old_pattern/new_pattern/g”,其中“g”代表全局匹配。 您需要的解决方案是:

sed -i "s/\"/\'/g" file.txt

这个sed应该可以工作

sed -E "s/([A-Za-z0-9])\"([^|].*)/\'/g" input_file

通过 sed 中的分组,您可以从匹配中排除无效引号 " 并在恢复组时替换它。

输出

"I'm a string"

我可能会想使用 perl

$ cat file.txt
"first"|"second"|"I"m a string"|"fourth"

$ perl -lne '
  print join "|",              # join, clearly
    map {"\"" . $_ . "\""}     # re-add outer quotes
    map {s/"/7/g; $_}       # replace inner quotes
    map {s/^"|"$//g; $_}       # remove leading/trailing quotes
    split /[|]/                # split the input on pipes
' file.txt
"first"|"second"|"I'm a string"|"fourth"

不过,正如 Shawn 评论的那样,用双引号替换内部引号可以为您提供有效的 CSV。

    map {s/"/""/g; $_}       # replace inner quotes

在每个 Unix 机器上的任何 shell 中使用任何 sed:

$ sed "s/\"/'/g; s/'|'/\"|\"/g; s/^'/\"/; s/'$/\"/" file
"String"|"I'm not a valid string"|"I'm a valid string"