【问题标题】:How to grep a variable which stores a full text file and print matching lines如何grep存储全文文件并打印匹配行的变量
【发布时间】:2025-10-23 14:05:02
【问题描述】:

您好,我一直在尝试执行一个代码,其中我使用变量 $logs 来保存我的所有 linux 日志。 现在我想 grep 模式的变量并打印其中包含模式的行的整行。 我想在我做 grep /pattern/ 的地方打印整行,并且必须打印其中有图案的行。 无论如何,这是我的代码。

my $logs = $ssh->exec("cat system_logs");
my $search = "pattern";

if(grep($search,$logs))
{
    # this is where i want to print the lines matched.
    # I want to print the whole line what command to use?
}

非常感谢任何帮助。

【问题讨论】:

  • 谢谢穆。对不起。忘记编辑了。

标签: perl


【解决方案1】:

试试这个:

foreach (grep(/$search/, split(/\n/, $logs))) {
    print $_."\n";
}

【讨论】:

  • 它不起作用。它打印所有匹配的行和不匹配的行。困惑:O
  • 我刚刚对搜索模式的指定方式做了一个小的修正。试试看。
  • 别忘了转义搜索模式。
最近更新 更多