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