我的 MacOS Catalina 上的grep
版本甚至没有-P
Perl 风格正则表达式的标志,
$ grep --version
grep (BSD grep) 2.5.1-FreeBSD
所以我只是推出了我自己的grep -l
命令版本,我需要获取与负前瞻正则表达式匹配的文件列表,下面是源代码,请随时适应您自己的需求,
#!/usr/bin/perl
use strict;
use warnings;
# Tries to mimic at least partially `grep -l` command, and provides support for look-arounds using Perl regex'
# Usage: ls <some folder> | grepList.pl <reg-ex>
# Algorithm:
# Open each file in the list supplied
# Apply regex to each line, as soon as it matches output file name to STDOUT and continue to next file
# If EOF file reached, means file did not match, do not print file name, and move on to next file
# Runtime complexity: O(m * n), where m is number of files and n is the maximum number of lines a file can have
# Space complexity: O(1), no intermediary memory storage needed
my $reg_ex = qr/$ARGV[0]/;
while(<STDIN>) {
chop($_);
my $file = $_;
open(IN, $file) || die "Unable to open $file: $!";
while(<IN>) {
my $line = $_;
if ($line =~ /$reg_ex/) {
print "$file\n";
last;
}
}
}