在 bash 中用不同的字符替换偶数和奇数引号

Replacing even and odd quotes with different characters in bash

提问人:user1902689 提问时间:9/24/2022 最后编辑:brian d foyuser1902689 更新时间:9/25/2022 访问量:79

问:

在 bash 中,使用 sed、awk、perl 或任何其他常用工具,如何转换如下行:

Some line
Some text "quoted" some other text "quoted again"

对此:

Some line
Some text [quoted] some other text [quoted again]

(对不起,忽略应用于这些代码块的颜色堆栈溢出。这不是故意的。

基本上,我希望用两个字符之一替换引号,具体取决于行中是偶数还是奇数引号。

我可以接受它在“格式不正确”的字符串上不能很好地工作,例如: 我不在乎它会把它改成This won"t work as intended because "someone" typed double quotes in the word won't instead of a single quote.This wo[t work as intended because ]someone[ typed double quotes in the word won't instead of a single quote.

(我实际上想做的是用 ANSI 颜色序列替换引用的文本,引用的文本,然后是 ANSI 颜色重置(返回白色)序列。但是,我正在简化问题,以便在这里使用。[]

与语言无关

评论

1赞 zdim 9/24/2022
什么是“关于”嵌套“引号”?

答:

-1赞 Polar Bear 9/24/2022 #1

以下演示代码假定带引号的部分在它开始的同一行结束。对于这种情况,应该使用简单的替换来代替。

use strict;
use warnings;

while( <DATA> ) {
    s/"([^"]+)"/[$1]/g;
    print;
}

__DATA__
Some line
Some text "quoted" some other text "quoted again"

输出

Some line
Some text [quoted] some other text [quoted again]
0赞 Darkman 9/24/2022 #2

用:sed

$ sed -E 's/"([^"]*)"?/[\1]/g' file
Some text [quoted] some other text [quoted again]
This won[t work as intended because ]someone[ typed double quotes in the word won't instead of a single quote.]

但它会在行的末尾放一个。这个没有。]

$ sed -E 's/"([^"]*)"/[\1]/g ; s/"([^"]*)$/[\1/' file
Some text [quoted] some other text [quoted again]
This won[t work as intended because ]someone[ typed double quotes in the word won't instead of a single quote.

这是另一种方法。

$ sed -E 's/"([^"]*)"/[\1]/g' file
Some text [quoted] some other text [quoted again]
This won[t work as intended because ]someone" typed double quotes in the word won't instead of a single quote.

评论

2赞 Ed Morton 9/24/2022
我只是去掉了你第一个正则表达式末尾的 - .没有必要使脚本复杂化,试图迎合 OP 说他们不关心的字符串,无论如何你都无法在这样的脚本中稳健地处理。?sed -E 's/"([^"]*)"/[\1]/g'