如果字符串的值大于零,则 Grep 之前的行

如果字符串的值大于零,则 Grep 之前的行

您好,我有一个包含以下信息的文本文件:

#[Tue Oct 25 00:00:02 2016] --- START OUTPUT
#CMD: XXX
END-->0<--
#[Tue Oct 25 00:00:57 2016] --- END
#RETURN: 1
#ELAPSED TIME (in seconds): 55

#[Tue Oct 25 00:05:01 2016] --- START OUTPUT
#CMD: XXX
END-->0<--
#[Tue Oct 25 00:05:33 2016] --- END
#RETURN: 0
#ELAPSED TIME (in seconds): 32

我想获取--End该行Return和该Elapsed行如果其对应的 Return 为>0。

到目前为止,我只能 grep Return 行grep "#RETURN:" -A 1 -B 1 f.log

>但是如何仅当 Return 为0时才 grep ?

期望的输出:

#[Tue Oct 25 00:00:57 2016] --- END
#RETURN: 1
#ELAPSED TIME (in seconds): 55

答案1

awk

awk '/END$/ {prev=$0; next}; /^#RETURN/ && $2>0 {cur=$0; pr=1; next};\
                      pr {printf "%s\n%s\n%s\n", prev, cur, $0; pr=0}' file.txt
  • /END$/ {prev=$0; next}:如果该行以 结尾END,则将其保存为变量prev,并转到下一行;这是之前的一行RETURN

  • /^#RETURN/ && $2>0 {cur=$0; pr=1; next}:如果该行以 开头#RETURN且第二个字段大于 0,则将该行保存为cur,将变量设置pr为 1(true),然后转到下一行

  • pr {printf "%s\n%s\n%s\n", prev, cur, $0; pr=0}:如果pr为true,则以所需格式打印输出,最后设置pr为0(false)

例子:

% cat file.txt                                                                                                                   
#[Tue Oct 25 00:00:02 2016] --- START OUTPUT
#CMD: XXX
END-->0<--
#[Tue Oct 25 00:00:57 2016] --- END
#RETURN: 1
#ELAPSED TIME (in seconds): 55

#[Tue Oct 25 00:05:01 2016] --- START OUTPUT
#CMD: XXX
END-->0<--
#[Tue Oct 25 00:05:33 2016] --- END
#RETURN: 0
#ELAPSED TIME (in seconds): 32

% awk '/END$/ {prev=$0; next}; /^#RETURN/ && $2>0 {cur=$0; pr=1; next}; pr {printf "%s\n%s\n%s\n", prev, cur, $0; pr=0}' file.txt
#[Tue Oct 25 00:00:57 2016] --- END
#RETURN: 1
#ELAPSED TIME (in seconds): 55

答案2

你可以试试这个;

awk -F: '/#RETURN:/ && $2 > 0 { getline; print $0}' test

例如;

user@host:/tmp$ awk -F: '/#RETURN:/ && $2 > 0 { getline; print $0}' test
#ELAPSED TIME (in seconds): 55

答案3

您应该在您的grep

 grep -C1 'RETURN: [1-9][0-9]*' input.txt

该正则表达式应该捕获不是单个 0(或不以 0 开头)的任何(正)数字。

相关内容