Replacing even and odd quotes with different characters in bash

Viewed 56

In bash, using sed, awk, perl, or any other common tool, how can I transform a line like these:

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

To this:

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

(Sorry, ignore the color stack overflow is applying to these code blocks. That isn't intended.)

Basically, I'm looking to replace a quote with one of two characters, depending on if it's an even or odd numbered quote in the line.

I'm fine with it not working well on "improperly formatted" strings like: This won"t work as intended because "someone" typed double quotes in the word won't instead of a single quote. I don't care that it'll change this to This wo[t work as intended because ]someone[ typed double quotes in the word won't instead of a single quote.

(What I'm actually trying to do is replace quoted text with an ANSI color sequence, the quoted text, then an ANSI color reset (back to white) sequence. But, I'm simplifying the problem to just use [ and ] here.)

2 Answers

Using 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.]

But it will put a ] at the end of the line. This one does not.

$ 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.

And this one is another approach.

$ 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.

The following demo code assumes that quoted section ends on same line it started. A simple substitution should do it for such case.

use strict;
use warnings;

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

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

Output

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