在连续行中搜索两个不同的单词,并仅打印两个连续行

2024-04-27 03:33:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含不同行的文件。我想搜索两个词“好”和“好” “12.2.1.1.6.180125.1”并打印两行。实际上第一行是主机名,第二行是版本,所以这需要放在一起。请建议如何使用python或shell查找?你知道吗

 ` cat file 

 microcldx0093.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}

microcldx0094.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}

microcldx0031.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}

microcldx0032.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}

microcldx0142.abc.com        : OK
{:output=>"12.1.2.3.4.170111", :exitcode=>0}

microcldx0157.abc.com        : OK
{:output=>"12.1.2.3.4.170111", :exitcode=>0}

microcldx0131.abc.com        : OK
{:output=>"12.1.2.3.4.170111", :exitcode=>0}

microcldx0136.abc.com        : OK
{:output=>"12.1.2.3.4.170111", :exitcode=>0}

`

 ` cat /tmp/1 |grep -e OK -e 12.2.1.1.6.180125.1
   microcldx0093.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}
microcldx0094.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}
microcldx0031.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}
microcldx0032.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}
microcldx0142.abc.com        : OK
microcldx0157.abc.com        : OK
microcldx0131.abc.com        : OK
microcldx0136.abc.com        : OK
 `

Tags: 文件comoutputokcatabcexitcodemicrocldx0142
2条回答

使用AWK

awk 'BEGIN {
    found = 0
}

/OK/ {
    okLine = $0;
    found = 1;
}

/12\.2\.1\.1\.6\.180125\.1/ {
    if (found = 1) {
        print okLine "\n"  $0
    } 
   found = 0
}

{
    found = 0
}' /tmp/1

BEGIN是在读取任何输入之前匹配的模式。这只是将found标志设置为零。你知道吗

/OK/模式与您要查找的第一行匹配。这将缓存该行并将found标志设置为1

下一个模式匹配你的数字。它必须避开点,因为它们是元字符。没有替罪羊,他们会匹配任何字符。如果found标志为1,则前一行必须与OK匹配。所以我们输出两行。我们现在重置标志,以便在首次匹配“确定”之前不会打印任何内容。你知道吗

最后一部分将匹配以前检查未匹配的任何内容。这将重置标志,以便我们必须再次开始查找OK。你知道吗

你可以试试: $cat文件| grep-A1正常| grep-B1'12.2.1.1.6.180125.1'

“grep-A1”给出包含“OK”的每一行加上后面的一行,在这些结果中,“grep-B1”给出包含“12.2.1.1.6.180125.1”的行加上前面的行,这应该给出您要查找的一对行。你知道吗

$ cat file | grep -A1 OK | grep -B1 '12.2.1.1.6.180125.1'
 microcldx0093.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}
 
microcldx0094.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}
 
microcldx0031.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}
 
microcldx0032.abc.com        : OK
{:output=>"12.2.1.1.6.180125.1", :exitcode=>0}

相关问题 更多 >