批量文件转码压缩打包Perl脚本

版权声明:本文为博主原创文章,转载请注明出处https://www.cnblogs.com/sgqhappy/p/9952614.html

我们经常遇到批量文件转码后压缩打包,为此我编写了一个Perl脚本,运行脚本文件后自动实现这些功能。

1.定义数组

#!/usr/bin/perl

use strict;

my @array=(
"110",
"120",
"130",
"140",
"150",
"210",
"212",
"220",
"230",
"310",
"320",
"330",
"332",
"340",
"350",
"352",
"360",
"370",
"372",
"410",
"420",
"430",
"440",
"443",
"450",
"460",
"500",
"510",
"520",
"530",
"540"
);

2.读取文件夹内容

my $utf8_path = "/tmp/";

#count the files.
my $file_count=0;

#get files_name.
my @file_name_array;
opendir(DIR,$utf8_path) or die "can't open the directory!";
@file_name_array=readdir DIR;

3.操作文件夹下的文件

这里运用了正则表达式,判断文件夹下的文件是否符合要求,如果符合,则进行后面的计算。

实现文件计数,文件名处理,转码等功能。

foreach my $file_name (@file_name_array){
    if($file_name=~/.*_M_0000_0000/){
        #print the file count.
        $file_count++;
        print "File number: ".$file_count."\n";
        
        #change files name
        my $mv="mv "."utf8_path"."/$file_name"." $utf8_path"."/$file_name".".utf8";
        `$mv`;
        print "$mv"."\n";
        
        #file_name from lower to upper.
        my $file_name_upper=uc(substr($file_name,0,(length($file_name)-4))).".txt";
        print "$file_name"."\n";
        print "$file_name_upper"."\n";
        
        #This is data cat from utf8 to gbk.
        my $cat="cat "."$utf8_path"."$file_name"." | iconv -f utf8 -t gbk -c > "."$utf8_path"."$file_name".".txt";
        
        #This is prompt message.
        print "cat "."$file_name"." success!"."\n\n";
    }else{
        print "$file_name "."is not the kind of file type you want!\n\n";
    }
}

4.将文件打tar包

#This is tar function.
my $tar="tar -zcvf "."gz.tar"." *.txt";
`$tar`;
print "$tar"." success!\n";

5.将tar包放到指定路径下

#loop every number,tar and move files to 36 directories.
foreach my $number(@array){
    #define path.
    my $gbk_path="/data/u"."$number"."/test/";
    my $cp="cp gz.tar "."$gbk_path";
    my $cp2="cp dl.tar "."$gbk_path";
    `$cp`;
    `$cp2`;
    print "$cp"." success! "."\n";
    print "$cp2"." success! "."\n";
};
print "============$file_count"." files cat"." success!!!=============\n";

 

作者:sgqhappy
出处:https://www.cnblogs.com/sgqhappy/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

posted @ 2018-11-13 16:01  sgqhappy  阅读(525)  评论(0编辑  收藏  举报
作者:sgqhappy 出处:https://www.cnblogs.com/sgqhappy/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。