我是Perl正则表达式的初学者。我正在从文本文档中读取内容并尝试提取与包含空格和特殊字符的所需字符串完全匹配的行,这是" hwsapbc05pvz ps -ef | grep prd | grep -v grep | wc -l"。以下是文本文档中的内容
spawn ssh -t -q -o StrictHostKeyChecking=no hwldbbc01pvs ps -ef |grep mysqld | grep -v grep | wc -l
spawn ssh -t -q -o StrictHostKeyChecking=no hwsapbc01pvb ps -ef |grep prd | grep -v grep | wc -l
spawn ssh -t -q -o StrictHostKeyChecking=no hwsapbc02pvc ps -ef |grep prd | grep -v grep | wc -l
spawn ssh -t -q -o StrictHostKeyChecking=no hwsapbc03pvg ps -ef |grep prd | grep -v grep | wc -l
spawn ssh -t -q -o StrictHostKeyChecking=no hwsapbc04pvv ps -ef |grep prd | grep -v grep | wc -l
spawn ssh -t -q -o StrictHostKeyChecking=no hwsapbc05pvz ps -ef |grep prd | grep -v grep | wc -l
spawn ssh -t -q -o StrictHostKeyChecking=no hwadbgw31pvv ps -ef |grep OpenDeploy | grep -v grep | wc -l
spawn ssh -t -q -o StrictHostKeyChecking=no hwadbgw32pve ps -ef |grep OpenDeploy | grep -v grep | wc -l
spawn ssh -t -q -o StrictHostKeyChecking=no hwawbgw01pvy ps -ef |grep sayt.*4150 | grep -v grep | wc -l
我写了代码
my $infile = "InputTextDoc.txt";
my $outfile = "Output.txt";
open(FH, "<$infile") or die "File not found";
open(OP, ">$outfile") or die "Output File not found";
my $str = "hwsapbc05pvz ps -ef |grep prd | grep -v grep | wc -l"; # which should only match 6th line from text document
while(<FH>)
{
$line = $_;
chomp($line);
if($line =~ m/\b$str\b/)
{
print OP "$line\n";
}
}
close FH;
close OP;
由于ps -ef存在于所有行中,因此匹配所有行。但是,整个字符串&#34; hwsapbc05pvz ps -ef | grep prd | grep -v grep | wc -l&#34;在文本文档中是唯一的 如何匹配精确的字符串。请帮忙。提前致谢
答案 0 :(得分:1)
如果将此变量包含在正则表达式中,解析器将使用管道
hwsapbc05pvz ps -ef |grep prd | grep -v grep | wc -l
↑ OR ↑ OR ↑ OR
在任何匹配的子字符串上给出匹配。要逐字匹配所有字符串,请尝试\Q escape
if($line =~ m/\b\Q$str\E\b/)
See demo at regex101或尝试使用quotemeta my $escaped_str = quotemeta($str);
答案 1 :(得分:1)
“|”在你的模式中需要用反斜杠转义,$ str需要在开头有qr。更改脚本的第5行,它适用于我的环境。
my $str = qr"hwsapbc05pvz ps -ef \|grep prd \| grep -v grep \| wc -l";
答案 2 :(得分:1)
subhas Chandra:我修改了你的代码并在下面发布了它。这应该工作正常。
use strict;
use warnings;
my $infile = "Input.txt";
my $outfile = "Output.txt";
open(FH, "<$infile") or die "File not found";
open(OP, ">$outfile") or die "Output File not found";
my $str = "hwsapbc05pvz ps -ef |grep prd | grep -v grep | wc -l"; # which should only match 6th line from text document
my $finalstr = quotemeta($str);
while(<FH>)
{
my $line = $_;
chomp($line);
if($line =~ m/$finalstr/)
{
print OP "$line\n";
}
}
close FH;
close OP;