1 |
#!/usr/bin/perl |
2 |
use strict; |
3 |
use Getopt::Std; |
4 |
use FindBin;use lib $FindBin::Bin; |
5 |
|
6 |
my $usage = q/Usage: |
7 |
batchcmds.pl [<shellcmds_file>] -f <datafile> [-t <delim>] |
8 |
|
9 |
<shellcmds_file> is a file containing an shell command(s) to be executed |
10 |
for each line in the <datafile>; if missing, the command is |
11 |
taken interactively from the standard input (use Ctrl+D to |
12 |
end the text input). Columns taken from <datafile> should |
13 |
be specified by placeholders :0 , :1 , .. :9 |
14 |
global authentication file, see note below) |
15 |
-f <datafile> should contain lines with space delimited fields; |
16 |
each field will replace the corresponding placeholders |
17 |
specified in the shellcmds_file (:0, :1 .. :9) |
18 |
/; |
19 |
umask 0002; |
20 |
my $qfile; |
21 |
$qfile=shift if (substr($ARGV[0],0,1) ne '-'); |
22 |
|
23 |
getopts('t:f:h') || die($usage."\n"); |
24 |
#my $outfile=$Getopt::Std::opt_o; |
25 |
if ($Getopt::Std::opt_h) { print $usage; exit;} |
26 |
|
27 |
die($usage."Error: shell command file not found!\n") |
28 |
unless (!$qfile || -e $qfile); |
29 |
|
30 |
my $datafile=$Getopt::Std::opt_f; |
31 |
die($usage."Error: data file $datafile not found.") unless (-e $datafile); |
32 |
|
33 |
my $delim=$Getopt::Std::opt_t; |
34 |
my $query=''; |
35 |
if ($qfile) { #qfile given |
36 |
local $/=undef;#one sip |
37 |
open(INFILE, '<'.$qfile); |
38 |
$query=<INFILE>; |
39 |
close(INFILE); |
40 |
} |
41 |
else { |
42 |
print STDERR ">Enter shell command(s) to be executed for each line of\n". |
43 |
" $datafile (use :1 .. :9 column placeholders; press Ctrl+D to end):\n"; |
44 |
local $/="\n"; |
45 |
$query.=$_ while (<STDIN>); |
46 |
} |
47 |
die("No placeholders found in the given commands. Aborting..\n") |
48 |
unless ($query =~ m/\:\d+/); |
49 |
|
50 |
$query=~s/\\[\n\r]+/ /sg; |
51 |
$query=~s/[\n\r]+/\x01/sg; |
52 |
my @cmds=split(/\x01/, $query); |
53 |
open(XLSTFILE, $datafile) || die ("Error opening data file $datafile !\n"); |
54 |
while (<XLSTFILE>) { |
55 |
chomp; |
56 |
#s/'/''/g; |
57 |
next unless $_; |
58 |
my @pdata; |
59 |
if ($delim) { |
60 |
@pdata=split(/$delim/); |
61 |
} |
62 |
else { |
63 |
@pdata=split(/\s+/); |
64 |
} |
65 |
#print STDERR ">dataline: $pdata[0] $pdata[1]\n"; |
66 |
foreach my $c (@cmds) { |
67 |
next if $c=~/^\s*$/s; |
68 |
my $cmd=$c; # copy value |
69 |
$cmd=~s/\:(\d+)\b/$pdata[$1]/sg; |
70 |
#the parameters are numbered from 0, not from 1 ! |
71 |
#so the first field from the file will be :0 |
72 |
# execute |
73 |
#print STDERR " .. exec: $cmd\n"; |
74 |
my $xcode=system($cmd); |
75 |
#sleep(1); |
76 |
print STDERR "Warning: error detected ($?) for command $cmd!\n" if $xcode; |
77 |
} |
78 |
} #for each param line |
79 |
close(XLSTFILE); |
80 |
|
81 |
#================ SUBROUTINES ============ |