1

I have a directory with thousands of file with following repetitive pattern containing hundreds of sections -

###############
# Section 1
###############
some text
more text
some more text
some text
more text
some more text    
###############
# Section 2
###############
some text
more text
some more text
interesting-pattern
some text
more text
some more text    
###############
# Section 3
###############
some text
more text
some more text
some text
more text
some more text

What i need to do is figure out a way to extract the entire SECTION where the "interesting-pattern" exists.

I have tried doing a grep -iEr 'interesting-pattern' with -A and -B flags but that doesnt work because in each file there could be different number of lines in the section before and after the intersting pattern.

What is the best way to do this?

0

This is not a job for grep , but for a better tool like awk.

The easy workaround is to use gnu awk with a customized record separator RS like Section.

Using word "Section" to separate lines, whatever is between words Section 1 and Section 2 will be considered as one line for awk.
Same for Section 2 - Section 3, etc.

Now you only need to print the correct "line" = the "line" that includes the interesting-pattern.

$ awk -v RS="# Section " '/interesting-pattern/{print RT $0}' file1
# Section 2
###############
some text
more text
some more text
interesting-pattern
some text
more text
some more text    
###############

Since gnu awk can accept regex in RS (Record Separator) you could also apply something more complicated in RS like this :

$ awk -v RS="###############\n# Section " '/interesting-pattern/{print RT $0}'
###############
# Section 2
###############
some text
more text
some more text
interesting-pattern
some text
more text
some more text    

PS: {print RT instructs awk to print the currently used Record Separator

  • 1
    Thanks George! I used your command and made a couple of tweaks to it to add recursive search and print filenames - for file in find ~/your-directory-path/ -type f ; do awk -v RS="###############\n#" '/interesting-pattern/{print FILENAME"\n", RT $0}' $file ; done . This recursively searches all files in "~/your-directory-path" , prints the file name before a match is found, prints a new line after the file name and then prints the matched section. – user168115 Jun 22 '17 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.