How do I replace double quotes with two different characters, based on their position in Bash?

Viewed 73

Say I have a file like:

""Lorem ipsum dolor sit amet, consectetuer adipiscing elit.""

And I’d like to transform it into german quotation:

"„Lorem ipsum dolor sit amet, consectetuer adipiscing elit.“"

I can use sed to replace the double quotes but how do I replace the leading pair of quotes with another character than the last pair of quotes?

4 Answers

This might work for you (GNU sed):

sed 's/""/\n/g;s/\n\([^\n]*\)\n/"„\1“"/g' file

Convert the pair "" into a unique delimiter e.g. a newline.

Then convert pairs of the unique delimiter to the required result.

N.B. If the pairs run over a line, then use the sed option -z to slurp the file into memory and use a different delimiter as newlines will no longer by unique.

With perl, matching per line:

perl -pe 's/""(.*?)""/"„$1“"/g'

To match across multiple lines:

perl -0777 -pe 's/""(.*?)""/"„$1“"/g'

For in-place editing, use perl -i or perl -i.bkp

Not using awk but using sed and pipes you can do something like.

sed "s/^\"\"/\"„/" /tmp/file | sed "s/\"\"$/“\"/" >> new_file;

The more fancy way to do it would be to use groups.

sed "s/^\"\"\(.*\)\"\"$/\"„\1“\"/" /tmp/file >> new_file

I am not accustomed to the Unicode characters you are using so you may have to tweak that.

With GNU awk for multi-char RS, RT, and gensub():

$ awk -v RS='""' '{ORS=gensub(RS,(NR%2 ? "\"„" : "“\""),1,RT)} 1' file
"„Lorem ipsum dolor sit amet, consectetuer adipiscing elit.“"
Another word … "„Lorem ipsum dolor sit amet, consectetuer adipiscing elit.“" and yet another word "„Even another sentence here“"
"„Lorem ipsum dolor
        sit amet, consectetuer
adipiscing elit.“"

The above will work even if your quoted text contains newlines and was run against this input file:

$ cat file
""Lorem ipsum dolor sit amet, consectetuer adipiscing elit.""
Another word … ""Lorem ipsum dolor sit amet, consectetuer adipiscing elit."" and yet another word ""Even another sentence here""
""Lorem ipsum dolor
        sit amet, consectetuer
adipiscing elit.""
Related