R – How to add characters at the beginning and end of every non-empty line in Perl

perlregex

I would like to use this:

perl -pi -e 's/^(.*)$/\"$1\",/g' /path/to/your/file

for adding " at beginning of line and ", at end of each line in text file. The problem is that some lines are just empty lines and I don't want these to be altered. Any ideas how to modify above code or maybe do it completely differently?

Best Answer

Others have already answered the regex syntax issue, let's look at that style.

s/^(.*)$/\"$1\",/g

This regex suffers from "leaning toothpick syndrome" where /// makes your brain bleed.

s{^ (.+) $}{ "$1", }x;

Use of balanced delimiters, the /x modifier to space things out and elimination of unnecessary backwhacks makes the regex far easier to read. Also the /g is unnecessary as this regex is only ever going to match once per line.

Related Topic