我写了一个脚本,它读取目录中的每个文件,执行某些操作并将每个输入文件的结果输出到两个不同的文件,例如“outfile1.txt”和“outfile2.txt”。我希望能够将生成的文件链接到原始文件,因此如何将输入文件名(infile.txt)添加到生成的文件名中,以获得如下内容:
infile1_outfile1.txt,infile1_outfile2.txt
infile2_outfile1.txt,infile2_outfile2.txt
infile3_outfile1.txt,infile3_outfile2.txt ......?
感谢您的帮助!
答案 0 :(得分:6)
使用替换从输入文件名中删除“.txt”。 使用字符串连接来构建输出文件名:
my $infile = 'infile1.txt';
my $prefix = $infile;
$prefix =~ s/\.txt//; # remove the '.txt', notice the '\' before the dot
# concatenate the prefix and the output filenames
my $outfile1 = $prefix."_outfile1.txt";
my $outfile2 = $prefix."_outfile2.txt";
答案 1 :(得分:4)
use File::Basename;
$base = basename("infile.txt", ".txt");
print $base."_outfile1.txt";
答案 2 :(得分:0)
简单字符串连接应该在这里工作,或者在cpan上查找适当的模块
答案 3 :(得分:0)
如果我理解正确,你在找这样的东西吗?
use strict;
use warnings;
my $file_pattern = "whatever.you.look.for";
my $file_extension = "\.txt";
opendir( DIR, '/my/directory/' ) or die( "Couldn't open dir" );
while( my $name_in = readdir( DIR )) {
next unless( $name_in =~ /$file_pattern/ );
my ( $name_base ) = ( $name_in =~ /(^.*?)$file_pattern/ );
my $name_out1 = $name_base . "outfile1.txt";
my $name_out2 = $name_base . "outfile2.txt";
open( IN, "<", $name_in ) or die( "Couldn't open $name_in for reading" );
open( OUT1, ">", $name_out1 ) or die( "Couldn't open $name_out1 for writing" );
open( OUT2, ">", $name_out2 ) or die( "Couldn't open $name_out2 for writing" );
while( <IN> ) {
# do whatever needs to be done
}
close( IN );
close( OUT2 );
close( OUT1 );
}
closedir( DIR );
编辑:实现了扩展剥离,输入文件句柄已关闭,现在已经过测试。