我有一个包含多个文件的目录。这些文件命名如下A11111,A22222,A33333,B11111,B22222,B33333等。我想读取这些文件,对内容执行某些格式化选项并将其写入输出文件。但是对于以A开头的所有文件,我只需要一个输出文件,对于以B开头的所有文件,我需要一个输出文件等等。是否有可能用perl脚本来做到这一点?使用perl脚本从目录中读取文件
0
A
回答
1
下面的例子应该是你一个良好的开端:
#!/usr/bin/perl
use strict;
use warnings;
my $dir = '.';
opendir my $dh, $dir or die "Cannot open $dir: $!";
my @files = sort grep { ! -d } readdir $dh;
closedir $dh;
$dir =~ s/\/$//;
foreach my $file (@files) {
next if $file !~ /^[A-Z](\d)\1{4}$/;
my $output = substr($file, 0, 1);
open(my $ih, '<', "$dir/$file") or die "Could not open file '$file' $!";
open(my $oh, '>>', "$dir/$output") or die "Could not open file '$output' $!";
$_ = <$ih>;
# perform certain formating with $_ here
print $oh $_;
close($ih);
close($oh);
}
在行next if $file !~ /^[A-Z](\d)\1{4}$/;
它跳过不在所需的格式,它是第一个字符是大写字母所有文件名,第二个是数字另外4个字符与第一个数字相同。
0
如果您在Linux上使用'猫文件1文件2 ...>工作大文件
否则这里是一个小的脚本来帮助你在路上
use strict;
use warnings;
# get the directory from the commandline
# and clean ending/
my $dirname = $ARGV[0];
$dirname =~ s/\/$//;
# get a list of all files in directory; ignore all files beginning with a .
opendir(my $dh, $dirname) || die "can't opendir $dirname: $!";
my @files = grep { /^[^\.]/ && -f "$dirname/$_" } readdir($dh);
closedir $dh;
# loop through the files and write all beginning with
# A to file A, B to file B, etc. extent the regex to fit your needs
foreach my $file (@files) {
if ($file =~ /([AB])\d+/) {
open(IN, "< $dirname/$file") or die "cant open $dirname/$file for reading";
open(OUT, ">> $dirname/$1") or die "cant open $dirname/$1 for appending";
print OUT <IN>;
close(OUT);
close(IN);
} else {
print "$file didn't match\n";
}
}
相关问题
- 1. 为什么Perl脚本以随机顺序从目录中读取文件?
- 2. Shell脚本从文件读取变量并在perl脚本中使用
- 3. Perl:读取目录,直到有文件
- 4. 的perl脚本 - 来读取XML文件
- 5. PHP从zip文件目录中读取文本文件
- 6. 使用文件流从根目录文件夹读取文件
- 7. 从目录中逐一读取文件
- 8. 从Scala目录中读取文件
- 9. 如何从目录中读取文件
- 10. 从目录中读取文件名
- 11. 从目录中逐一读取文件
- 12. 从文件 - shell脚本中读取值
- 13. Python脚本从csv文件中读取
- 14. 从脚本中读取TDM(Diadem)文件
- 15. 从新贵脚本中读取文件
- 16. 如何读取从perl脚本
- 17. 通过从文本文件读取文件名从目录中移动文件
- 18. Javascript从当前目录中读取文本文件
- 19. 从文本文件中读取目录时会发生变化
- 20. 我可以转换此Perl脚本以使其从文件中读取吗?
- 21. 使用C脚本读取YAML文件
- 22. 从目录中读取文件并从Java中过滤文件
- 23. 使用xcode从Documents目录中读取文件
- 24. 使用NSBundle从自定义目录中读取图像文件
- 25. 使用matlab从目录中读取多个文件
- 26. 使用bash脚本从文件中读取行
- 27. 如何使用perl脚本获取目录的属性?
- 28. 使用Perl从文本文件中提取文本
- 29. 是否可以使用Perl读取pdf文件中的文本?
- 30. Shell或Perl脚本,从文本文件
这是可能的。 [你有什么试过?](http://whathaveyoutried.com)[显示你的进度和代码。](http://stackoverflow.com/questions/how-to-ask)解释你在没有其他。 – daxim
你问这是否可能,或者是否有人会提供代码来完成它?这当然是可能的 – mathematician1975
任何事情都可能与Perl! – Jean