有人能告诉我为什么find命令总是转到根目录而不是指定的目录$srceDir吗?
my $srceDir = "/mnt/SDrive/SV/Capture Data/";
my $find_cmd = 'find $srceDir -type f -newermt 2013-02-14 ! -newermt 2013-02-15';
open(FIND_FILE, "$find_cmd |");
while(<FIND_FILE>){
next if /^total/; # because we're only interested in real output
print $_;
}
Run Code Online (Sandbox Code Playgroud)
因为您使用单引号而不是双引号。
Perl 不会插入用单引号括起来的变量,因此您所做的是将字符串 '$srceDir' 发送到通常不会设置(空白)的 shell,除非您在环境中的某处设置了它。
尝试这个:
my $find_cmd = "find $srceDir -type f -newermt 2013-02-14 ! -newermt 2013-02-15";
Run Code Online (Sandbox Code Playgroud)
或者更好:
my $find_cmd = sprintf
'find "%s" -type f -newermt 2013-02-14 ! -newermt 2013-02-15',
$srceDir;
Run Code Online (Sandbox Code Playgroud)
...关心空格,而find_cmd将在forked下执行sh。
* 重要备注 *
正如@vonbrand 正确评论的那样:perl确实提供了许多库来确保您的程序与许多其他事物之间的通信。
对于文件系统操作find,perl 使用File库模块File::Find,为此存在一个小实用程序find2perl,它将您的find命令行转换为一个小 perl 脚本:
$ find2perl -type f -mtime -3 ! -mtime -2;
#! /usr/bin/perl -w
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
if 0; #$running_under_some_shell
use strict;
use File::Find ();
# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.
# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name = *File::Find::name;
*dir = *File::Find::dir;
*prune = *File::Find::prune;
sub wanted;
# Traverse desired filesystems
File::Find::find({wanted => \&wanted}, '.');
exit;
sub wanted {
my ($dev,$ino,$mode,$nlink,$uid,$gid);
(($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
-f _ &&
(int(-M _) < 3) &&
! (int(-M _) < 2)
&& print("$name\n");
}
Run Code Online (Sandbox Code Playgroud)
所以你的需求可能会变成这样:
#! /usr/bin/perl -w
my $srceDir = "/mnt/SDrive/SV/Capture Data/";
my $startDate = "2013-02-14";
my $endDate = "2013-02-15";
use strict;
use File::Find ();
use POSIX qw|mktime|;
use vars qw/*name *dir *prune/;
*name = *File::Find::name;
*dir = *File::Find::dir;
*prune = *File::Find::prune;
my ($sDay,$eDay)=map {
my ($year,$month,$day)=split("-",$_);
(time()-mktime(0,0,0,$day,$month-1,$year-1900))/86400
} ($startDate,$endDate);
sub wanted {
my ($dev,$ino,$mode,$nlink,$uid,$gid);
(($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
-f _ &&
(-M _ < $sDay) &&
! (-M _ < $eDay)
&& print("$name\n");
}
File::Find::find({wanted => \&wanted}, $srceDir );
Run Code Online (Sandbox Code Playgroud)
这样做而不是 的最大优点open $fh,"find ...|"是它非常健壮;您不必关心文件名中存在的字符(如空格、引号、&符号...)。
| 归档时间: |
|
| 查看次数: |
16817 次 |
| 最近记录: |