#!/usr/bin/perl
use Getopt::Long;
GetOptions(
"help!"=>\$helpopt,
"key=s"=>\$keyopt,
"field-separator=s",\$ifsopt,
"output-separator=s",\$ofsopt,
"database=s",\$optdb,
"verbose",\$verbose
);
if ($helpopt) {
print "splitk [OPTION] [INPUT]\n";
print " --help - this message\n";
print " -k, --key=POS1[,POS2,...] - key is field combination of field
positions\n";
print " -f, --field-separator=SEP - use SEP instead of whitespace for
IFS\n";
print " -o, --output-separator=SEP - use SEP instead of ',' for OFS\n";
print " -d, --database=db - use DB hash file \"db\" to store values\n";
print " -v, --verbose - display warnings to stderr\n";
exit 1;
}
my $ifs = $ifsopt;
my $key = ($keyopt eq '') ? '' : $keyopt;
my @key = grep($_--, split(',', $key)); # Perl arrays start at "0", not "1"
@key = (0) unless @key;
foreach (@key) { /^[0-9]+$/ || die "Invalid key number \"$_\"\n"; }
my %found;
if ($optdb) {
use DB_File;
tie %found, 'DB_File', $optdb || die "Open DB_File $optdb: $!\n";
}
my $ofs = ($ofsopt eq '') ? ',' : $ofsopt;
while (<>) {
chop;
my @line = ($ifs eq '') ? split() : split(/$ifs/, $_);
my $f = join($ofs,(@line)[@key]);
$found{$f} .= "$_\n";
}
my $value;
while (($f,$value) = each %found) {
# if ($f =~ /-\w,\.:\{\}=\+\_\^\%\#\@\~\!/o) {
if (open(F,">$f")) {
print F $value;
} else {
warn "Could not write $f: $!\n" if $verbose;
print STDOUT $value;
}
# } else {
# warn "Invalid filename: $f\n";
# print STDOUT $value;
# }
}
What I need to do is before the printf to the file above... is
1. Set mydir = first field of the key value - delimiter is a dot such as key value is ns1.ford.com .. mydir should = ns1
2. ck if mydir exists and create if not
3. mydir should get into the code below where the $f ile gets written
4. the print F $value needs to append to the file not overwrite it. Maybe it always does and the problem is that the script is creating the file every time it runs.
here was one way of ck if dir exists and create if not, that i found
$dir = 'c:/mike/tmp oops space/';
unless(-d $dir){
mkdir $dir or die "Couldn't create dir: [$dir] ($!)";
}