首页 > 解决方案 > 如何在文件bash中循环打开和结束字符串?

问题描述

我正在编写一个 shell 脚本来遍历字符串并在该测试用例中出现该单词时回显匹配项。

我有一个看起来像的文件

/*
  some build info #which are not matter of interest
*/
Test: TestCase_one
.
.
   output of that testcase 
   #TestCase_one name will not be present in btw
.
.
TestCase_one passed 
Test: TestCase_two
.
.
   output of that testcase
.
.
   TestCase_two passed 
   many testcases in this pattern
/*
   some thread info
*/

在上面的文件中,我想检查每个测试用例的特定单词,如果该单词存在则回显匹配,为此我想循环遍历每个测试用例的文件,然后逐步移动到文件末尾

有没有办法开始在 TestCase_one 和 TestCase_one Passed 之间寻找一个词等等?

我没有 shell 脚本方面的背景,任何建议或手册页来实现这一点都会对我有所帮助。

预期输出应该看起来像

TestCase_one
No matches
TestCase_TWo
.
.
  matched lines
.
.

提前致谢

标签: bashshellawkscriptinggrep

解决方案


我假设你是什么:

在“Test: Testcase”和“TestCase_.*passed”之间搜索字符串“foo”。如果匹配,则打印匹配的行。

你能不能简单地做:

cat bigfile | grep -E '(foo|^Test: TestCase)'

它不会完全符合您的预期输出(例如,不会打印“无匹配” - 不会有任何匹配),但它非常接近且非常简单。

如果您不想要所有测试用例但想查看单个测试用例,那么这可能对您有用:

cat file |
  perl -ne '/^Test: Testcase start/ .. /Test case end/ and /foo/ and print'

它将搜索foo但仅介于Test: Testcase start和之间Test case end。如果要在输出中包含起始行,请使用:

cat file |
  perl -ne '/^Test: Testcase start/ .. /Test case end/ and /^Test: Testcase start|foo/ and print'

推荐阅读