Skip to content

Commit

Permalink
grep: search binary files (#795)
Browse files Browse the repository at this point in the history
* When testing against OpenBSD and GNU versions, the meaning of -a is to list the matching lines of a binary file 
* Without -a, binary files should be searched but only a "Match" message should be printed
* Change the current meaning of -a to make this version more compatible
* Update pod manual and description in usage()

%perl grep BASH /bin/bash
grep: /bin/bash: binary file matches
%echo $?
0
%perl grep BASH /bin/echo
%echo $?
1
%perl grep -a BASH /bin/bash
/usr/share/bashdb/bashdb-main.inccannot start debugger; debugging mode disabledrbash/bin/shI have no name!??host??run_one_command-cENVBASH_ENVHISTFILEcannot set uid to %d:
...
%echo $?
0
%perl grep -a BASH /bin/echo
%echo $?
1
  • Loading branch information
mknos authored Nov 11, 2024
1 parent 2c9634f commit 3df6b6e
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions bin/grep
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ use File::Spec;
use File::Temp qw();
use Getopt::Std;

our $VERSION = '1.008';
our $VERSION = '1.009';

$| = 1; # autoflush output

Expand Down Expand Up @@ -113,7 +113,7 @@ Options:
-r recursive on directories or dot if none
-p paragraph mode (default: line mode)
-P ditto, but specify separator, e.g. -P '%%\\n'
-a all files, not just plain text files
-a treat binary files as plain text files
-s suppress errors for failed file and dir opens
-T trace files as opened
Expand Down Expand Up @@ -371,6 +371,7 @@ sub matchfile {
$total = 0;

FILE: while ( defined( $file = shift(@_) ) ) {
my $is_binary = 0;
my $compressed = 0;

if ( $file eq '-' ) {
Expand Down Expand Up @@ -422,9 +423,8 @@ FILE: while ( defined( $file = shift(@_) ) ) {
$file = "$Compress{$ext} $file |";
$compressed = 1;
}
elsif (!$opt->{'a'} && -B $file) {
warn qq($Me: skipping binary file "$file"\n) if $opt->{T};
next FILE;
elsif (-B $file) {
$is_binary = 1;
}
}

Expand All @@ -447,6 +447,7 @@ FILE: while ( defined( $file = shift(@_) ) ) {
$Errors++;
next FILE;
}
binmode($fh) if $is_binary;
}

$total = $Matches = 0;
Expand All @@ -472,6 +473,10 @@ FILE: while ( defined( $file = shift(@_) ) ) {
print $name, "\n";
last LINE;
}
if ($is_binary && !$opt->{'a'}) {
warn "$Me: $file: binary file matches\n";
last LINE; # single match for binfile unless -a
}
unless ($opt->{'c'}) {
print($name, ':') if $Mult;
print $opt->{n} ? "$.:" : "", $_,
Expand Down Expand Up @@ -533,8 +538,7 @@ Allow at most one match per file.
=item B<-a>
Search all files. The default is to only search plain text files
and compressed files.
List matching lines from binary files as if they were plain text files.
=item B<-C>
Expand Down

0 comments on commit 3df6b6e

Please sign in to comment.