how to grep one string occuring multiple times from same file

杀马特。学长 韩版系。学妹 提交于 2019-12-02 23:45:36

问题


I want to capture a string 1 row affected... But problem is there are no of such string present in the same file.

My concern to capture 1 row affected.. only which is present after the string UPDATE kplustp..Service SET Service_Name = "PositionService", ServiceType = \'Z\', Hostname = " " in log file. 1 row affected.. will be present after 3 4 sentences from Job completed successfully.

I am working on solaris.

How to do?


回答1:


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



回答2:


If you have GNU grep, you can make use of its ability to display trailing context of matches:

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

The first grep will look for the string Job completed successfully, while also providing the five subsequent lines. It is in those lines that the other grep looks for 1 row affected, and prints the match.




回答3:


Assuming some input like

$ 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...

Let's say you only want the first row after "Job completed successfully" that contains "row affected". You can pipe it like so

| 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...

Where the sed matches any line containing Job completed successfully and returns from that line to the end of the file and grep -m NUM shows only the first NUM matches of grep. Could probably do it with one sed thought that gets more messy. If grep -m NUM is unavailable, you can just pipe to head, e.g.

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


来源:https://stackoverflow.com/questions/21256070/how-to-grep-one-string-occuring-multiple-times-from-same-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!