输出表中数据的匹配
我们需要逐个元素匹配某些数据,该元素是在命令提示符下获得的表格形式的输出。以下是当前遵循的方法,其中 $Var 包含输出。是否有一种最佳方法可以在不将命令输出定向到文件的情况下执行此操作。
请分享您的想法。
$Var = "iSCSI Storage LHN StgMgmt Name IP Name
==============================================================
0 Storage_1 15.178.209.194 admin
1 acct-mgmt 15.178.209.194 storage1
2 acct-mgmt2 15.178.209.194 storage2";
@tab = split("\n",$Var);
foreach (@tab) {
next if ($_ !~ /^\d/);
$_ =~ s/\s+//g;
$first=0 if($_ =~ /Storage/i && /15.178.209.194/);
push(@Array, $_); }
We need to match certain data element by element that is an output in tabular form obtained on the command prompt.The following is the approach being currently followed wherein the $Var contains the output. Is there an optimal way of doing this without directing the command output to file.
Please share your thoughts.
$Var = "iSCSI Storage LHN StgMgmt Name IP Name
==============================================================
0 Storage_1 15.178.209.194 admin
1 acct-mgmt 15.178.209.194 storage1
2 acct-mgmt2 15.178.209.194 storage2";
@tab = split("\n",$Var);
foreach (@tab) {
next if ($_ !~ /^\d/);
$_ =~ s/\s+//g;
$first=0 if($_ =~ /Storage/i && /15.178.209.194/);
push(@Array, $_); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
$_ =~ /Storage/i && /15.178.209.194/
很愚蠢。像这样分解:($_ =~ /Storage/i) && (/15.178.209.194/)
。要么一致使用$_
,要么不使用 -//
和s///
运算符自动对$_
.您还应该知道,在正则表达式
/15.178.209.194/
中,.
被解释为任何字符。要么转义它们,要么使用index()
函数。此外,我建议您使用 split() 分隔每一行。这使您可以比较每个单独的列。您可以将
split()
与正则表达式一起使用,如下所示:@array = split(/\s+/, $string);
。最后,我不太确定
$first
的用途,但我注意到该输入中的所有三个示例行都会触发$first=0
因为它们都包含该 IP和字符串“存储”。$_ =~ /Storage/i && /15.178.209.194/
is silly. That gets broken up like this:($_ =~ /Storage/i) && (/15.178.209.194/)
. Either use$_
consistently or don't - the//
ands///
operators automatically operate on$_
.Also you should know that in the regex
/15.178.209.194/
, the.
s are being interpreted as any character. Either escape them or use theindex()
function.Additionally, I would recommend that you separate each line using
split()
. This allows you to compare each individual column. You can usesplit()
with a regex like so:@array = split(/\s+/, $string);
.Finally, I'm not really sure what
$first
is for, but I notice that all three sample lines in that input trigger$first=0
as they all contain that IP and the string "storage".如果我理解正确的话,你想像这样调用你的脚本:
你想要使用的是 Perl 钻石运算符
<>
:我已经删除了
$_< 的冗余使用/code> 并修复了您的替换,因为您可能不想删除所有空格。
If I understand you correctly you want to invoke your script like this:
What you want to use is the Perl diamond operator
<>
:I've removed the redundant uses of
$_
and fixed your substitution, since you probably don't want to remove all spaces.