In a real-world production environment, it is often necessary to intercept messages from the background logs in a form similar to
<InterBOSS>
...
...
...
</InterBOSS>
A background log has multiple messages, each of which can be determined by the operation flow only.
Previously written in awk, the program is as follows:
Beginline= 'awk 'begin{i=0}{if ($0~ "<InterBOSS>") i=nr;if ($0~ "'$oprseq'") {Print I;exit}}'$logname' EndLine=`awk 'nr>'$beginline'{if ($0~ "</InterBOSS>") {print Nr;exit}}'$logname`awk 'nr>='$beginline'&&nr<='$endline'{print $}'$logname
After learning Perl, I found that Perl was a great fit for writing logic-like scripts, which are now rewritten as follows:
#!/usr/bin/perl UseStrict;my $flag=0;my $line; while(<>){ if(/<interboss>/or$flageq1){ $line.=$_; $flag=1; } if(/<\/interboss>/){ $flag=0; if($line=~$ARGV[0]){ Print $line; Last; } $line="'; }}
The idea is:
Each message as a whole, put into the $line, and then verify whether the given operation flow is in $line, if the output $line, if not, then the $line is empty, continue to loop until the next message is encountered <interboss>,$ Line only starts filling.
So how do you make sure that the lines between <InterBOSS> and </InterBOSS> are populated into $line? Here, the introduction of a variable $flag to judge, the default is 0, when encountered <InterBOSS>, set it to 1, in the encounter </InterBOSS>, and then set it to 0. There are two criteria to determine if the fill is: one, match <interboss>, two, $flag equals 1, both of which can be used to ensure that rows between <InterBOSS> and </InterBOSS> are populated to $ In line.
How to intercept messages in Perl