Here's one way to do it... This is a little fragile given that the fields "last name, first name" and "city, state" need to be in the same place in the list of elements in the line. If there's a comma in the data in the fields between the name and "city, state" fields, the code won't work. If you know that those fields aren't going to contain commas, you should be fine.
#!/usr/bin/perl -w
use strict;
my $file = "question.lst";
my $newfile = "question2.lst";
my @newlines;
open(FILE, "<$file") || die "$!\n";
chomp(my @lines = <FILE>);
close FILE;
foreach(@lines) {
s/\t/,/g; # substitute commas for any tabs
# This keeps the field delimiters all the same
# If your data is going to have tabs in it,
# remove that line
my @elements = split(/,/, $_);
# since the split splits the last and first name,
# and the "City, State" fields
# join them back together and remove the unnecessary
# elements
$elements[0] = "$elements[0],$elements[1]";
$elements[4] = "$elements[4], $elements[5]";
splice(@elements, 1, 1);
splice(@elements, 4, 1);
# If the elements aren't already enclosed in quotes,
# enclose them.
foreach(@elements) {
$_ = qq("$_") unless (m/\".*\"/);
}
# Join the elements of the line back together
# and push them to a new array
my $newline = join(",", @elements);
push(@newlines, $newline);
}
# Print the information to a new file
open(NEWFILE, ">$newfile") || die "$!\n";
foreach(@newlines) {print NEWFILE "$_\n";}
close NEWFILE;
Here's the input file (question.lst)...
"Smith, Robert",94 N. Orange Grove,# 25,West Hollywood,CA,90046,(323)5
+55-1234,931
"Jones, Bob" 111 S. Orange Grove # 72 Silverlake,CA 90210,
+(323)555-5555,931
Here's the output file (question2.lst)...
"Smith, Robert","94 N. Orange Grove","# 25","West Hollywood, CA","9004
+6","(323)555-1234","931"
"Jones, Bob","111 S. Orange Grove","# 72","Silverlake, CA","90210","(3
+23)555-5555","931"
Hope that helps... |