forked from briandfoy/PerlPowerTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxargs
executable file
·109 lines (93 loc) · 2.46 KB
/
xargs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/perl
=begin metadata
Name: xargs
Description: construct argument list(s) and execute utility
Author: Gurusamy Sarathy, gsar@umich.edu
License:
=end metadata
=cut
#
# An xargs clone.
#
# Gurusamy Sarathy <gsar@umich.edu>
#
use strict;
use File::Basename qw(basename);
use Getopt::Std qw(getopts);
use Text::ParseWords qw(quotewords);
use constant EX_SUCCESS => 0;
use constant EX_FAILURE => 1;
my $Program = basename($0);
my %o;
getopts('0tn:L:l:s:I:', \%o) or die <<USAGE;
Usage:
$Program [-0t] [-n num] [-L num] [-s size] [-I repl] [prog [args ...]]
-0 expect NUL characters as separators instead of spaces
-t trace execution (prints commands to STDERR)
-n num pass at most 'num' arguments in each invocation of 'prog'
-L num pass at most 'num' lines of STDIN as 'args' in each invocation
-s size pass 'args' amounting at most to 'size' bytes in each invocation
-I repl for each line in STDIN, replace all 'repl' strings in 'args'
before execution
USAGE
for my $opt (qw( L l n s )) {
next unless (defined $o{$opt});
if (!length($o{$opt}) || $o{$opt} =~ m/\D/) {
warn "$Program: option $opt: invalid number '$o{$opt}'\n";
exit EX_FAILURE;
}
if ($o{$opt} == 0) {
warn "$Program: option $opt: number must be > 0\n";
exit EX_FAILURE;
}
}
$o{'L'} = $o{'l'} if defined $o{'l'};
my @args = ();
$o{I} ||= '{}' if exists $o{I};
$o{l} = 1 if $o{I};
my $sep = $o{'0'} ? '\0+' : '\s+';
my $eof = 0;
while (!$eof) {
my $line = "";
my $totlines = 0;
while (<STDIN>) {
$eof = eof;
chomp;
next unless (length && m/\S/);
$line .= $_ if $o{I};
$totlines++;
my @words = quotewords($sep, 1, $_);
push @args, grep { defined } @words;
last if $o{n} and @args >= $o{n};
last if $o{s} and length("@args") >= $o{s};
last if $o{'L'} and $totlines >= $o{'L'};
}
my @run = @ARGV;
push @run, 'echo' unless (@run);
if ($o{I}) {
exit(EX_SUCCESS) unless length $line;
for (@run) { s/\Q$o{I}\E/$line/g; }
}
elsif ($o{n}) {
exit(EX_SUCCESS) unless @args;
push @run, splice(@args, 0, $o{n});
}
else {
exit(EX_SUCCESS) unless @args;
push @run, @args;
@args = ();
}
if ($o{t}) { local $" = "', '"; warn "exec '@run'\n"; }
my $rc = system @run;
if ($rc == -1) {
warn "$Program: $run[0]: $!\n";
exit EX_FAILURE;
}
if ($rc && $rc >> 8 == 255) {
warn "$Program: $run[0]: exited with status 255\n";
exit EX_FAILURE;
}
}
=encoding utf8
=head1 NAME
xargs - construct argument list(s) and execute utility