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";
    }
}

相关内容

热门资讯

市值首次站上4万亿美元后,英伟... 英伟达的供应链遍布全球,在中国台湾,墨西哥、越南等多个国家及地区都有生产基地及市场。为了与中国市场保...
投资者提问:董秘你好,我觉得深... 投资者提问:董秘你好,我觉得深蓝和阿维塔产品都非常不错,但公司需要一个资深营销总监,把现在的销售团队...
特朗普遭未遂刺杀案:美特勤局6... 据美国广播公司(ABC)10日报道,一名美国官员证实,因在去年针对当时的总统候选人特朗普的未遂刺杀案...
拓斯达拟为润阳世纪光伏提供不超... 2025年7月11日,广东拓斯达科技股份有限公司发布关于向客户提供融资租赁回购担保的公告,拟为江苏润...
中国第一家保险公司的保单原来在... 转自:上观新闻今年的7月8日是第13个全国保险公众宣传日,由上海市保险学会、上海市保险同业公会联合策...
防溺水“压力山大”,南昌为何仍... 转自:半月谈 #南昌免费开放两滩七湾天然泳场# 【防溺水...
汽车行业今日净流出资金26.7... 沪指7月11日上涨0.01%,申万所属行业中,今日上涨的有19个,涨幅居前的行业为非银金融、钢铁,涨...
联合国设立“世界马日” 向人... 中新网北京7月11日电 据联合国新闻官网消息,今年的7月11日是联合国大会通过投票设立的首个“世界马...
Mhy20250711油脂晚评... (转自:南京玛合雅)一、【市场关注】1、北京时间7月10日(周四)中午12:30,马来西亚棕榈油局M...
25股股东户数连降 筹码持续集... 投资者可以在交易所互动平台上通过提问方式了解部分公司更及时(每月10日、20日、月末)的股东户数信息...