我有一个名为malwareip.txt的文件,列表为IP:
1.1.1.1
2.2.2.2
我需要从这个文件中读取并创建另一个文件(query.txt),以便最终结果为:
ip.dst=1.1.1.1 || ip.dst=2.2.2.2
我创建了以下脚本。 。但是我在第一行中看到||
如下:
||ip.dst=1.1.1.1
||ip.dst=2.2.2.2
为什么我在||
之前收到ip.dst=1.1.1.1
?
请参阅下面的我的脚本。感谢。
#!/usr/bin/env perl
use strict;
use warnings;
my $filename="malwareip.txt";
open (my $ip, "<" , $filename) || die ("Can't open file malwareip.txt");
my $outputfile="query.txt";
open (my $out, ">" , $outputfile) || die ("CAN'T OPEN FILE query.txt");
my $OR="||";
while ( <$ip> ) {
next if (/^$/);
printf $out "ip.dst=$_$OR";
}
close $out;
close $ip;
答案 0 :(得分:2)
您当前的输出没有意义,因为除非您在那里打印,否则无法在输出开头获取||
。即使您的文件中碰巧有空行也不会,因为它仍会在该空行之前打印ip.dst=
。所以,你必须弄错输出或输入代码。
因为您忘记了chomp
您的输入,您通常会得到这样的输出
ip.dst=1.1.1.1
||ip.dst=2.2.2.2
||
如果您有非标准的行结尾,例如使用CR \r
的文件,那么您的所有行都会被覆盖,但您只能获得一行输出:最后一行。
||ip.dst=2.2.2.2
所以你的输出毫无意义,直到你提供更多信息才能解释。
如果我要这样做,我会这样做:
perl -lwe 'chomp(@a = <>); print join "||", grep /\S/, @a;' malwareip.txt > query.txt
答案 1 :(得分:0)
chomp
。||
,即使您想要少打印也是如此。 s/\s+\z//
会扼杀LF和CRLF行结尾。
my $OR = '';
while ( <$ip> ) {
s/\s+\z//;
next if /^$/;
print $out "${OR}ip.dst=$_";
$OR = ' || ';
}
print $out "\n";
请注意使用print
而不是printf
。 printf
期望其第一个参数是格式参数。
print $out "${OR}ip.dst=$_"; # ok
printf $out "%s", "${OR}ip.dst=$_"; # ok
printf $out "%sip.dst=%s", $OR, $_; # ok
printf $out "${OR}ip.dst=$_"; # Not really ok