【问题标题】:Find a string in a file and if it matches, find another matching string before it in the file [closed]在文件中查找一个字符串,如果匹配,则在文件中找到另一个匹配的字符串 [关闭]
【发布时间】:2020-10-08 08:41:04
【问题描述】:

我有一个包含数据的文件,如下例所示:


读取文件1
错误1
错误2
错误3
读取文件2
错误1
错误3
错误6
读取文件3
错误2
错误3
错误6


我想搜索Error2,如果找到,它的文件名是file1和file3。

我知道如何单独搜索匹配项,但想知道在找到匹配项后如何向后搜索另一个匹配项。

【问题讨论】:

  • 首先搜索文件名,然后检查您找到的每个文件名是否包含与您的错误条件匹配的内容。向后搜索不是一个容易解决的问题。
  • 有很多可以用来解决这类问题的模式示例,比如我最近的回答stackoverflow.com/questions/62447462/…

标签: shell perl search


【解决方案1】:

我认为这是获取输出的漫长方法,但你肯定会得到。

my $file_nm = "";
while( my $line = <DATA> )
{
    chomp($line);
    if($line=~m/Reading\s+(.+)/)
    {
        $file_nm = $1;
    }
    if($line=~m/Error2/)
    {
        print "$line - found in $file_nm\n";
    }
}

__DATA__
Reading file1
Error1
Error2
Error3
Reading file2
Error1
Error3
Error6
Reading file3
Error2
Error3
Error6

输出:

Error2 - found in file1
Error2 - found in file3

【讨论】:

  • 当然...谢谢冠军,我会尽快更新。 +感谢您的指导。
猜你喜欢
  • 1970-01-01
  • 2020-03-25
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
相关资源
最近更新 更多