我读了一篇类似的帖子,标题为"只有当下一行与模式不匹配时才打印匹配模式的行",所提到的解决方案是
awk 'a=/^O/{x=$0} !a&&x{print x;x=0;}' myfile
Run Code Online (Sandbox Code Playgroud)
我只是想知道如果我想打印下一行也以与当前行相同的模式开始的文件中的所有行,上述命令将如何改变.
例如
文件文本包含:
abc this is a line
def
abc this is line 2
ghi
abc this is line 3
abc this is line 4
jkl
mno
abc this is line 5
jkl
abc this is line 6
abc this is line 9
jkl
Run Code Online (Sandbox Code Playgroud)
该命令应该只打印以下行:
abc this is line 3
abc this is line 6
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
感谢所有帮助过的人.在这里编辑原始问题以满足要求,因为当存在多个相似的行时,以下将无济于事.
如果要打印文件中的所有行以使下一行以不同的模式结束,那么awk命令会是什么?
例如:如果文件包含:
Student name is A
Student name is B
Student name is C
result for C is pass
Student name is D
result for D is pass
Student name is E
result for E is pass
Student name is F
result for F is pass
Student name is G
result for G is pass
Student name is H
Student name is I
result for I is pass
Run Code Online (Sandbox Code Playgroud)
如何使用awk打印学生姓名未通过的所有行.因此,对于上面的示例,打印的行应为:
Student name is A
Student name is B
Student name is H
Run Code Online (Sandbox Code Playgroud)
我可以打印所有以Student开头的行,其后续行不以字符串PASS结尾使用awk吗?
编辑:
对于更新的要求:
我可以打印所有以Student开头的行,其后续行不以字符串PASS结尾使用awk吗?
$ awk '$NF != "pass" && p0 {print p0} {p0 = ($1 == "Student") ? $0 : ""}' sw.txt
Student name is A
Student name is B
Student name is H
Run Code Online (Sandbox Code Playgroud)
上一篇:
打印文件中的所有行,其下一行也以与当前行相同的模式开始.
$ awk '$1 == p1 {print p0} {p1 = $1; p0 = $0}' sw.txt
abc this is line 3
abc this is line 6
Run Code Online (Sandbox Code Playgroud)
如果当前第一个字段与前一行字面匹配,则打印上一行.
(我应该注意,虽然你的问题是指以相同"模式"开头的行,但基于样本输入和输出,我认为这意味着简单的字符串匹配而不是正则表达式,因为"模式"通常指的是在awk的上下文中.)