获取文件中匹配项后的特定行

获取文件中匹配项后的特定行

我有一个具有这种模式的日志文件

Time = 100

GAMG:  Solving for p, Initial residual = 0.2174470886, Final residual = 0.01001676933, No Iterations 1
GAMG:  Solving for p, Initial residual = 0.02692910633, Final residual = 0.0004864615367, No Iterations 2
GAMG:  Solving for p, Initial residual = 0.005753534485, Final residual = 0.0001502172182, No Iterations 2
GAMG:  Solving for p, Initial residual = 0.001526301953, Final residual = 5.384448346e-05, No Iterations 2
GAMG:  Solving for p, Initial residual = 0.0004529702305, Final residual = 1.80754637e-05, No Iterations 1
time step continuity errors : sum local = 2.722585271, global = 0.09763545089, cumulative = 0.09763545089
ExecutionTime = 27.35 s  ClockTime = 31 s

Time = 101

GAMG:  Solving for p, Initial residual = 0.04799119366, Final residual = 0.002390404161, No Iterations 1
GAMG:  Solving for p, Initial residual = 0.02803010067, Final residual = 0.0009371130484, No Iterations 2
GAMG:  Solving for p, Initial residual = 0.007210353379, Final residual = 0.0002494798057, No Iterations 2
GAMG:  Solving for p, Initial residual = 0.002410795933, Final residual = 0.000116871876, No Iterations 2
GAMG:  Solving for p, Initial residual = 0.0007431402835, Final residual = 1.649739876e-05, No Iterations 3
GAMG:  Solving for p, Initial residual = 0.0003489407136, Final residual = 1.262095062e-05, No Iterations 1
time step continuity errors : sum local = 0.7142966337, global = -0.1125594528, cumulative = -0.01492400189
ExecutionTime = 41.42 s  ClockTime = 45 s

Time = 102

之后的线Time =总是Iterations 1,我想得到那条线。我尝试过这些想法:

使用 grep,如果我写grep -A 2 "Time =" test.txt,它会显示

Time = 100

GAMG:  Solving for p, Initial residual = 0.2174470886, Final residual = 0.01001676933, No Iterations 1

ExecutionTime = 27.35 s  ClockTime = 31 s

Time = 101

如果我使用 awkcat test.txt | awk '/Time/{getline;getline;print}'会显示

GAMG:  Solving for p, Initial residual = 0.2174470886, Final residual = 0.01001676933, No Iterations 1
Time = 101
Time = 102

那些Time = 101Time = 102是之后的两行ExecutionTime

简而言之,我只想获得第一个非空行,之后Time =我知道它总是Iterations 1。我怎样才能得到它?

答案1

如果您想绝对确定打印以No Iterations 1一行结尾的第一行Time = ...,您可以使用以下awk命令:

awk '/^Time =/ {f=1} /No Iterations 1$/ && f {f=0; print}' test.txt

awk命令有两条规则({ ... })。

  • ^Time =如果该行与正则表达式匹配,即以字符串开头,则处理第一个Time =。在此规则中,我们只需设置一个标志f1指示已找到模式的“起始线”。
  • No Iterations 1$如果该行与正则表达式匹配,即处理下一个结束用字符串No Iterations 1,我们之前已经找到了Time =- 行。如果满足两个条件,则打印该行,并f重置标志,以便我们不会打印以下任何以No Iterations 1.

一个更“宽松”的变体,它只是打印语句后的第一个非空行Time = ...(不检查它是否包含模式No Iterations 1)是:

awk '/^Time =/ {f=1; next} NF>0 && f {f=0; print}' test.txt

这只是查看该标志是否f已设置,并且NF该行中的“字段数”(或列数,如果您愿意的话)是否大于零。请注意,在这里,我们必须next在第一个规则中添加一个命令以跳过执行到下一行,否则 -ruleNF>0将已经针对Time =-lines 进行处理,从而有效地仅打印这些 -lines。

对于您的示例,两者都打印:

GAMG:  Solving for p, Initial residual = 0.2174470886, Final residual = 0.01001676933, No Iterations 1
GAMG:  Solving for p, Initial residual = 0.04799119366, Final residual = 0.002390404161, No Iterations 1

相关内容