Skip to content

Commit 4e61810

Browse files
authored
head: allow '+' prefix on line count (#1044)
* The standards document says -n COUNT counts from one [1] * The OpenBSD and GNU versions accept a '+' prefix on a number, so allow that here for compat Tests: perl head -2 head --> 2 lines perl head -n2 head --> 2 lines perl head -n+2 head --> 2 lines perl head -n-2 head --> invalid 1. https://pubs.opengroup.org/onlinepubs/9799919799/utilities/head.html
1 parent ac78257 commit 4e61810

1 file changed

Lines changed: 7 additions & 5 deletions

File tree

bin/head

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use constant EX_SUCCESS => 0;
2121
use constant EX_FAILURE => 1;
2222

2323
my $Program = basename($0);
24-
my ($VERSION) = '1.3';
24+
my ($VERSION) = '1.4';
2525

2626
@ARGV = new_argv();
2727
my %opt;
@@ -32,11 +32,11 @@ unless (getopts('n:', \%opt)) {
3232
my $count;
3333
if (defined $opt{'n'}) {
3434
$count = $opt{'n'};
35-
if (length($count) == 0 || $count =~ m/[^0-9]/) {
35+
if ($count !~ m/\A[\-\+]?[0-9]+\Z/) {
3636
warn "$Program: invalid number '$count'\n";
3737
exit EX_FAILURE;
3838
}
39-
if ($count == 0) {
39+
if ($count <= 0) {
4040
warn "$Program: count is too small\n";
4141
exit EX_FAILURE;
4242
}
@@ -89,6 +89,7 @@ sub head_fh {
8989
sub new_argv {
9090
my @new;
9191
my $end = 0;
92+
my $prev = '';
9293

9394
foreach my $arg (@ARGV) {
9495
if ($arg eq '--' || $arg !~ m/\A\-/) {
@@ -97,11 +98,12 @@ sub new_argv {
9798
next;
9899
}
99100

100-
if (!$end && $arg =~ m/\A\-([0-9]+)\Z/) { # historic
101+
if (!$end && $prev ne '-n' && $arg =~ m/\A\-([0-9]+)\Z/) { # historic
101102
push @new, "-n$1";
102103
} else {
103104
push @new, $arg;
104105
}
106+
$prev = $arg;
105107
}
106108
return @new;
107109
}
@@ -133,6 +135,7 @@ I<head> accepts the following options:
133135
=item -n count
134136
135137
Print I<count> lines instead of the default 10.
138+
The number must be a positive decimal integer.
136139
137140
=back
138141
@@ -164,4 +167,3 @@ and sell this program (and any modified variants) in any way you wish,
164167
provided you do not restrict others to do the same.
165168
166169
=cut
167-

0 commit comments

Comments
 (0)