updated git and svn scripts
[xrzperl.git] / foreach
blobb2b2a3df7a83e686e75c4442a222eb9f36c039cd
1 #!/usr/bin/perl -w
2 ###APPNAME: foreach
3 ###APPAUTHOR: duel
4 ###APPDATE: Sat May 29 19:18:48 2010
5 ###APPVER: 0.1
6 ###APPDESC: run commands against every matched filename
7 ###APPUSAGE: [-f|-d] [wildcard] [cmds|cmds "{}" args...]
8 ###APPEXAMPLE: foreach -d '*' echo mv '"{}"' ..
9 ###APPOPTION: -f:Select files only|-d:select directories only
10 use strict;
12 #ENV variable MUST be defined somewhere,
13 #FOR perl to search modules from,
14 #OR nothing will work
15 use lib $ENV{XR_PERL_MODULE_DIR};
17 use MyPlace::Script::Usage qw/help_required help_even_empty/;
18 exit 0 if(help_required($0,@ARGV));
19 #exit 0 if(help_even_empty($0,@ARGV));
21 sub run {
22 print STDERR " ",join(@_),"\n";
23 return system(@_) == 0;
26 my $cmd_place_holder_str = '"{}"';
27 my $cmd_place_holder_exp = qr/\{\}/;
29 my $exp;
30 my @cmds;
31 my $opt;
32 my $opt_status='';
34 foreach(@ARGV) {
35 if($opt_status eq 'cmd') {
36 push @cmds,$_;
38 elsif($_ eq '-d') {
39 $opt='-d';
41 elsif($_ eq '-f') {
42 $opt='-f';
44 else {
45 $exp = $_;
46 $opt_status='cmd';
49 @cmds = ('echo','"{}"') unless(@cmds);
50 $exp = "*" unless($exp);
52 my $cmds_replacable = 0;
53 foreach(@cmds) {
54 if($_ =~ $cmd_place_holder_exp) {
55 $cmds_replacable = 1;
56 last;
60 use File::Glob qw/bsd_glob/;
62 foreach my $filename (bsd_glob($exp)) {
63 if($opt and $opt eq '-d') {
64 next unless(-d $filename);
66 elsif($opt and $opt eq '-f') {
67 next unless(! -d $filename);
70 if($cmds_replacable) {
71 my @cmds_new = @cmds;
72 foreach my $word (@cmds_new) {
73 $word =~ s/$cmd_place_holder_exp/$filename/g;
75 &run(@cmds_new);
77 else {
78 &run(@cmds,$filename);