The UNIX and Linux Forums  


Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #3 (permalink)  
Old 01-05-2009
pludi's Avatar
pludi pludi is online now Forum Staff  
Moderator
  
 

Join Date: Dec 2008
Location: .at
Posts: 1,921
This Perl script might help you. It takes 2 arguments:
  1. Seperator used (in your example ' ')
  2. Table for inserting (in your example 'table_xyz')
The data itself is read from standard input, the INSERT statements are print to standard out.

Code:
#!/usr/bin/perl -W

use strict;
use warnings;

my $sep   = $ARGV[0];
my $table = $ARGV[1];
while ( my $line = <STDIN> ) {
    print "INSERT INTO $table VALUES(";
    my @line = split /$sep/, $line;
    for ( my $i = 0 ; $i < $#line ; $i++ ) {
        $_ = $line[$i];
        if (/\D/) {
            print '"', $_, '"';
        }
        else {
            print $_;
        }
        print ',' if $i < $#line - 1;
    }
    print ");\n";
}

Your example would give
Code:
$ perl csv2sql.pl ' ' table_xyz < example.txt
INSERT INTO table_xyz VALUES(123,4536,"abcd4",677,"bbb","ggg","nnn");
INSERT INTO table_xyz VALUES(343,5656,"abcd6",566,"eee","fff","ooo");
INSERT INTO table_xyz VALUES(343,5645,"abcd7",556,"ddd","lll","jjj");
$