Shell – Count lines matching pattern and matching previous line

grepshell-scripttext processingwc

I want to count the number of times that a role is successfully deleted. The problem is that one line of the log file will show that the script is about to delete the role:

Prepare to remove role X

The next line will tell me if the delete is successful or not:

Successful delete:

Delete Successful

Unsuccessful delete:

Failed to delete role X: error code

How do I count the number of successful Role deletes? I would just use the following grep:

grep "Delete Successful" | wc -l

HOWEVER, I am also deleting policies which is logged in the same manner as the roles are above. IE:

Prepare to delete policy X
Delete Successful

OR

Failed to delete policy X: error code

Any way to search for "Prepare to delete role" on one line and then count the number of times the very next line says "delete successful?"

Best Answer

If your grep is the GNU grep, here is a quick and dirty solution:

grep -A1 "Prepare to remove role" | grep "Delete Successful" | wc -l

The grep option -A1 tells grep to print the matching line AND one line following the matching line. The second grep then only prints the lines where the delete is successfull.

Note that this will only work reliably when the "Prepare to remove role X" line is always immediately followed by the "Delete Successful" line.

Also note: you don't need wc -l because grep has that functionality built in:

grep -A1 "Prepare to remove role" | grep -c "Delete Successful"
Related Question