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:
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!
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:
-XXX
lines and the following lines+xxx
line cannot also be a -xxx
lineTherefore, any +xxx
lines must be following lines, and should be counted, which we do with wc -l
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With