Tuesday, March 15, 2022

[SOLVED] Find string followed by blank line followed by string with grep

Issue

I have a large number of text files and inside some of them there is the following text:

++++

++++

So, that's four '+' characters, then a "\n" symbol (at least, I think it is, to be honest I'm not 100% sure), then a blank line, then another "\n" symbol (I think!) then four '+' characters again.

I want to write a grep to find such line combinations in these files.

I am open to using any other commands such as sed/ awk, if they produce the same result.

Here is my attempt:

grep '++++\n^$\n++++' *

Solution

With awk:

awk '/^++++$/ { plusnum=NR;plusstr=$0 } /^$/ && plusnum==(NR-1) { print plusstr;print $0 }' file*.txt

Check for a line with only "++++", set a variable plusnum to the record number (NR) and set a variable plusstr to the line ($0). Then when there is an empty line and the previous line/record number (NR-1) is the same as plusnum, print plusstr and the existing line.



Answered By - Raman Sailopal
Answer Checked By - Clifford M. (WPSolving Volunteer)