tags:

views:

135

answers:

6

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?

+7  A: 
perl -pi -e 's/^(.+)$/\"$1\",/g' /your/file

.* matches 0 or more characters; .+ matches 1 or more.

You may also want to replace the .+ with .*\S.* to ensure that only lines containing a non-whitespace character are quoted.

Wooble
+4  A: 

change .* to .+

In other words lines must contain at 1 or more characters. .* represents zero or more characters.

RET
+4  A: 

You should be able to just replace the * (0 or more) with a + (1 or more), like so:

perl -pi -e 's/^(.+)$/\"$1\",/g' /path/to/your/file
Hank Gay
+2  A: 
sed -r 's/(.+)/"\1"/' /path/to/your/file
Mark Byers
+4  A: 

all you are doing is adding something to the front and back of the line, so there is no need for regex. Just print them out. Regex for such a task is expensive if your file is big.

gawk

$ awk 'NF{print "\042" $0 "\042,"}' file

or Perl

$ perl -ne 'chomp;print "\042$_\042,\n" if ($_ ne "") ' file
ghostdog74
Doesn't that modify the empty lines too? He said he didn't want that.
Mark Byers
easy to fix. done
ghostdog74
Just to be pedantic, in the Perl version, you want `if $_ ne ''` rather than just `if $_`. `$_` will evaluate as false for certain non-empty lines (specifically, those containing a lone 0).
Dave Sherohman
ghostdog74
+7  A: 

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.

Schwern
that makes it a lot more readable, thanks!
Phil