如何grep从同一文件多次出现的字符串

时间:2014-01-21 10:55:04

标签: linux bash unix solaris

我想捕获一个字符串1 row affected..。但问题是同一个文件中没有这样的字符串。

我担心只捕获日志文件中字符串1 row affected..之后的UPDATE kplustp..Service SET Service_Name = "PositionService", ServiceType = \'Z\', Hostname = " "。来自1 row affected..的3 4个句子后,Job completed successfully将出现。

我正在开发solaris。

怎么办?

3 个答案:

答案 0 :(得分:1)

perl -e 'while (<>) { if (/job completed successfully/) { $flag=1; } elsif (/1 row affected/) { print; } else { $flag=0; } }'

答案 1 :(得分:1)

如果你有GNU grep,你可以利用它显示匹配的尾随上下文的能力:

cmd... | grep -A 5 "Job completed successfully" | grep "1 row affected"

第一个grep会查找字符串Job completed successfully,同时还会提供五个后续行。另一个grep寻找1 row affected并在那些行中打印匹配。

答案 2 :(得分:0)

假设有一些输入,如

$ printf "1 row affected...\nsomeline\nsomeline\nJob completed successfully\nsomeline\nsomeline\n2 row affected...\n3 row affected...\n"
1 row affected...
someline
someline
Job completed successfully
someline
someline
2 row affected...
3 row affected...

假设您只想要“Job completed successfully”之后的第一行包含“受影响的行”。你可以像这样管道它

| sed -n -e '/Job completed successfully/,$p' | grep -m 1 "affected"

e.g

$ printf "1 row affected...\nsomeline\nsomeline\nJob completed successfully\nsomeline\nsomeline\n2 row affected...\n3 row affected...\n" | sed -n -e '/Job completed successfully/,$p' | grep -m 1 "row affected"
2 row affected...

sed匹配任何包含Job completed successfully的行,并从该行返回到文件末尾,grep -m NUM仅显示grep的第一个NUM匹配。可能会因为一个sed的想法变得更加混乱。如果grep -m NUM不可用,您只需输入head,例如

| sed -n -e '/Job completed successfully/,$p' | grep "affected" | head -n 1