Perl-->文件的操作
创始人
2024-02-22 08:54:28
0

1,从一个文件的完全路径中找出它的文件名

#!/usr/bin/perl -w

use File::Basename;
$path = "/home/sysadmin/test/aaa.txt.html";
$basename = basename($path, ".html");
print $basename . "\n";


我们只需要把文件的完全路径,还有要剔除的扩展名传给它,如果没有第二个参数,就取出完整文件名。



2,对目录进行递归搜索


#!/usr/bin/perl -w

use File::Find;

$path = '/home/sysadmin/test';

find(\&handleFind, $path);

sub handleFind {
    my $foundFile = $File::Find::name;
    print "$foundFile\n" if ($foundFile =~ /\.html?$/i);
}




3,一次读入整个文件内容。


#!/usr/bin/perl -w

$path = '/home/sysadmin/test/aaa.txt.html';
open FH, "< $path";
$/ = undef;
$slurp = ;
print $slurp;


打开文件的另外一种方法:


#!/usr/bin/perl

use warnings;

$file = '/etc/passwd';

open PASSWD, "< $file"
 or die "How did you get logged in? ($!)";

while(){
     print $_;
}



4,删除某个目录下的特征文件


#!/usr/bin/perl -w

use File::Find;

$path = '/home/sysadmin/test';

find(\&wanted, $path);

sub wanted {  
      if (-f $File::Find::name)  
             {  
               if ($File::Find::name=~/\.cvs$/i or $File::Find::name=~/\.jpg$/i)
                   {  
                      print "Removing $File::Find::name\n";  
                             unlink   $File::Find::name;  
                    }  
              }  
}




5,复制文件或者目录


#!/usr/bin/perl

use warnings;

use File::Copy;

$source = '/etc/passwd';
$target = '/usr/local/src';
 
copy( "$source", "$target" ) or die "Copy failed: $!";


另外一种方法:

#!/usr/bin/perl

use warnings;

$source = "/home/jive/";
$target = "/usr/local/src";

system("cp -rdp $source $target");



5,移动文件


#!/usr/bin/perl

use warnings;

use File::Copy;

$source = '/home/sysadmin/lvs';
$target = '/usr/local/src';

move( "$source", "$target" ) or die "Copy failed: $!";



6,找出指定目录下的文件和目录


$dir = "/home/sysadmin/aa";

opendir(DIR,"$dir") or die "Can't open the current directory: $!\n";

@names = readdir(DIR) or die "Unable to read current dir:$!\n";

closedir(DIR);

foreach $name (@names) {
    next if ( $name =~ /^\./ );
    if ( -d $name ) {
        print "found $dir directory: $name\n";
        next;
    }
    else {
        print "found $dir file: $name\n";
    }
}

相关内容

热门资讯

中证A500ETF摩根(560... 8月22日,截止午间收盘,中证A500ETF摩根(560530)涨1.19%,报1.106元,成交额...
A500ETF易方达(1593... 8月22日,截止午间收盘,A500ETF易方达(159361)涨1.28%,报1.104元,成交额1...
何小鹏斥资约2.5亿港元增持小... 每经记者|孙磊    每经编辑|裴健如 8月21日晚间,小鹏汽车发布公告称,公司联...
中证500ETF基金(1593... 8月22日,截止午间收盘,中证500ETF基金(159337)涨0.94%,报1.509元,成交额2...
中证A500ETF华安(159... 8月22日,截止午间收盘,中证A500ETF华安(159359)涨1.15%,报1.139元,成交额...
科创AIETF(588790)... 8月22日,截止午间收盘,科创AIETF(588790)涨4.83%,报0.760元,成交额6.98...
创业板50ETF嘉实(1593... 8月22日,截止午间收盘,创业板50ETF嘉实(159373)涨2.61%,报1.296元,成交额1...
港股异动丨航空股大幅走低 中国... 港股航空股大幅下跌,其中,中国国航跌近7%表现最弱,中国东方航空跌近5%,中国南方航空跌超3%,美兰...
电网设备ETF(159326)... 8月22日,截止午间收盘,电网设备ETF(159326)跌0.25%,报1.198元,成交额409....
红利ETF国企(530880)... 8月22日,截止午间收盘,红利ETF国企(530880)跌0.67%,报1.034元,成交额29.0...