Delete CSV record
Hello,
Can anyone help me with a way of deleting records from a CSV file using perl? Or does anyny know of a script out there that can do such.
I am working on a script to manipulate a CSV file via a web browser but I can't quite figure out how to delete records from it. . Please Help
Thanks
Mizzy
ROB posted this at 16:23 — 26th August 2002.
They have: 447 posts
Joined: Oct 1999
i believe PHP has built in csv functions, although i've never used them. as for perl, i wrote a script to convert .csv files into tab-delimmeted files because csv is such a ***** to work with. also, you must consider microsoft has a different implementation of csv than most other companies (doesnt that apply to everything?)
anyways, here it is, hope it's helpful:
#!/usr/bin/perl
# parse_csv.pl
# convert a .csv file into tab-delimmeted text file
# usage: perl parse_csv.pl infile outfile
# example: perl parse_csv.pl /home/myfiles/mydata.csv /home/myfiles/mydata.txt
my ($infile) = @ARGV;
my $tmpfile = $infile;
$tmpfile =~ s/^.*[\\\/]//;
$tmpfile =~ s/[\\\/]//g;
$tmpfile = '/tmp/tmp_' . $tmpfile;
## hack to get rid of multi-line records
open(INFILE,$infile);
open(TMPFILE,">$tmpfile");
while(<INFILE>) {
$_ =~ s/\s*$//;
next if $_ eq '';
if($_ =~ m/,"[^,"]*$/) {
print TMPFILE "$_ ";
}
else {
print TMPFILE "$_\n";
}
}
close INFILE;
close TMPFILE;
### parse the file
open(TMPFILE,$tmpfile);
my $rowcnt = 0;
while(<TMPFILE>) {
++$rowcnt;
my $newline = "";
my @row = ();
while ($_ =~ /\G\s*(?!$)("[^"]*(?:""[^"]*)*"|[^,"]*),?/g) {
push @row, $1;
$row[-1] =~ s/\s+$//;
if ($row[-1] =~ s/^"//) {
chop $row[-1]; $row[-1] =~ s/""/"/g;
}
}
map {
$_ =~ s/\t/ /g;
$newline .= "$_\t";
} @row;
$newline =~ s/\t$/ /;
print "$newline\n";
}
close(TMPFILE);
unlink($tmpfile);
exit;
once it's in tab-delimmeted format, you can access each 'field' by doing something like this:
my @fields = split(/\t/, $row);
if you need to keep the data in csv format, you can modify the above code to check each row for specific values and either print the csv line back to file (rather than the tabbed line) or skip to the next line
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.