Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to find if two adjacent new lines start with certain words?

Tags:

grep

bash

sed

perl

Say I have a file like so:

+jaklfjdskalfjkdsaj
fkldsjafkljdkaljfsd
-jslakflkdsalfkdls;
+sdjafkdjsakfjdskal

I only want to find and count the amount of times during this file a line that starts with - is immediately followed by a line that starts with +.

Rules:

  • No external scripts
  • Must be done from within a bash script
  • Must be inline

I could figure out how to do this in a Python script, for instance, but I've never had to do something this extensive in Bash.

Could anyone help me out? I figure it'll end up being grep, perl, or maybe a talented sed line -- but these are things I'm still learning.

Thank you all!

like image 823
James Roseman Avatar asked May 31 '13 11:05

James Roseman


1 Answers

grep -A1 "^-" $file | grep "^+" | wc -l

The first grep finds all of the lines starting with -, and the -A1 causes it to also output the line after the match too.

We then grep that output for any lines starting with +. Logically:

  1. We know the output of the first grep is only the -XXX lines and the following lines
  2. We know that a +xxx line cannot also be a -xxx line

Therefore, any +xxx lines must be following lines, and should be counted, which we do with wc -l

like image 134
Tom Dalton Avatar answered Sep 22 '22 13:09

Tom Dalton