我有以下文件,包括测试和失败的内容(如果失败):
[Initial]
[Connect]
[Check]
FAILED cable orientation
[Power]
[Test1]
FAILED speed test
FAILED continuity
[Test2]
[Test restart]
文件语法为:
我想过滤掉失败的测试(测试名称和失败)。所以在这个例子中我将得到以下输出:
[Check]
FAILED cable orientation
[Test1]
FAILED speed test
FAILED continuity
我尝试使用sed和awk这样做但是失败了。
答案 0 :(得分:1)
根据测试文件的时长,您可能希望使用此文件:
grep "FAILED" file.txt -B1
在给定的文本文件上运行此命令将产生:
[Check]
FAILED cable orientation
--
[Test1]
FAILED speed test
FAILED continuity
如果您不想要连字符,可以通过将grep
添加到sed '/--/d'
来删除连字符,或者您可以尝试使用--no-group-separator
选项(我不是确定grep
的所有版本都附带此选项,因此我会坚持使用sed
)。
因此运行grep "FAILED" file.txt -B1 | sed '/--/d'
会产生:
[Check]
FAILED cable orientation
[Test1]
FAILED speed test
FAILED continuity
答案 1 :(得分:0)
懒惰的解决方案将使用tac
工具:
tac file|awk '/^FAILED/{f=1;print}/^\[/{if(f)print;f=0}' |tac
试验:
kent$ cat f
[Initial]
[Connect]
[Check]
FAILED cable orientation
[Power]
[Test1]
FAILED speed test
FAILED continuity
[Test2]
[Test restart]
kent$ tac f|awk '/^FAILED/{f=1;print}/^\[/{if(f)print;f=0}' |tac
[Check]
FAILED cable orientation
[Test1]
FAILED speed test
FAILED continuity