loops - 将后跟与模式匹配的行打印到文件 A,如果不匹配则打印到文件 B
问题描述
我正在尝试编写一个 Perl 脚本来解析文件并根据匹配条件分离其内容。一个示例文件(例如 test.txt)看起来像这样:
command something something keyword something something
filepath1
filepath2
command something something something something
filepath3
filepath4
filepath5
脚本的输出将是基于脚本输入文件名的两个文件,test.keyword 和 test.nomatch。
test.keyword 会是这样的:
command something something keyword something something
filepath1
filepath2
test.nomatch 会是这样的:
command something something something something
filepath3
filepath4
filepath5
我已经尝试寻找实现这一目标的方法,但我找不到对我有帮助的东西。这是我剧本中唯一剩下的部分,现在让我发疯了。是的,我不是 Perl 专家。:(
以下是我目前正在等待黄金循环条件的骨架:
#!/usr/bin/perl -a
my $fh = shift or die "No file passed as argument for splitting!\n";
open( infile, "<$fh" ) or die $!;
open( vef_output, ">$fh.vef" ) or die $!;
open( svf_output, ">$fh.svf" ) or die $!;
$mode = 0; #0 for vef and 1 for svf
while ( my $line = <$infile> ) {
if ( $line =~ /SOME_LIBRARY_OPTIONS/ ) {
if ( $line =~ /\-sv/ ) {
print {$svf_output} $line;
$mode = 1;
}
else {
print {$vef_output} $line;
$mode = 0;
}
next;
}
if ( $mode eq 0 ) {
print {$vef_output} $line;
next;
}
else {
print {$svf_output} $line;
next;
}
}
close($vef_output);
close($svf_output);
close($file);
解决方案
虽然您的代码逻辑是正确的,并且您肯定会自己发现一些剩余的拼写错误,但我想建议您对 while 循环进行修改:
输入文件的每一行都必须打印一次(可能除了开头输入文件)。$mode
我宁愿切换输出 filehandle ,而不是设置标志并测试它,这会导致更清晰的代码:
#!/usr/bin/perl
use strict;
use warnings;
my $filename = shift or die "No file passed as argument for splitting!\n";
# add filename to error message - users will like it!
open( my $infile, "<", $filename ) or die "could not open $filename: $!";
open( my $vef_output, ">","$filename.vef" )
or die "could not open $filename.vef: $!";
open( my $svf_output, ">","$filename.svf" )
or die "could not open $filename.svf: $!";
my $active_out;
while ( my $line = <$infile> ) {
if ( $line =~ /SOME_LIBRARY_OPTIONS/ ) {
$active_out = $vef_output;
}
# depending on your regex this conditional can be nested or not...
if ( $line =~ /-sv/ ) {
$active_out = $svf_output;
}
next unless defined $active_out;
print $active_out $line;
}
close($vef_output);
close($svf_output);
close($infile);
推荐阅读
- erpnext - 电子邮件没有自动创建为 ERPNext 中的问题
- android - 如何在android中为特定屏幕尺寸添加尺寸
- c# - 无法通过 EWS 托管 API 从电子邮件中下载 FileAttachment
- python - Python:如何创建一个在本地保存并在运行之间持续存在的变量
- ruby-on-rails - 我正在进行新的迁移以在 ROR 中的两个实体之间创建关联。我在迁移中使用了错误的实体,需要将其删除
- aws-api-gateway - 第 7 层负载均衡器 vs API 网关 vs 负载均衡器 + 路由服务
- database - 为什么重启 influxdb 后读取访问需要时间?
- javascript - 创建等高按钮
- .net-core - 是否可以将 IAgent 接口注入到 .net 核心 DI 容器
- android - File_Picker 插件不返回 Flutter 中写入文件的绝对路径