Given a file of strings, one sring per line, I want to write a script to make the file usable by SQL: each string should lie within single quotes, a comma should follow each quoted string (except the last), and the whole bunch should be enclosed by parens. I'd prefer to read the file in line by line, but I am wondering if that will let me acomplish what I want to do. For a file:
one
two
three
I want:
('one',
'two',
'three')
this sed script seems to work:
sed -e s/\(.*\)/'\1',/g -e 1s/\(.*\)/(\1/ -e $s/\(.*\),/\1)/$s/\(.*\),/\1)/
but I was hoping perl could do it more readably or simply. The last line, where the comma should be missing, is hard to achieve. This is what I have so far:
use strict;
my $line;
while(<>){
chomp;
s/^/'/g;
s/$/',/g;
if($.==1){ s/^/(/;}
print $_,"\n";
$line=$_;
# this is where I am stuck; I need to test if we are at the last line.
}
but you can see that the last line isn't quite right.
Any thoughts?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.