Here it is in GNU sed
:
sed '/./{H;$!d};x;/SEARCH/!d'
Portable/POSIX syntax:
sed -e '/./{H;$!d;}' -e 'x;/SEARCH/!d'
If a line contains one or more characters it is appended to H
old space and if it is !
the $
last line it is deleted. This means every line that is not a blank gets stored and removed from output.
So if a line is not d
eleted then sed
ex
changes the contents of hold and pattern space. This makes the hold space only a blank line and the pattern space all lines since the last blank line.
sed
then addresses the pattern /SEARCH/
. If !
not found it d
eletes the pattern space without printing, else the paragraph is printed by default.
Here it is in a shell function with your question as input :
Note - the processed data is commented below for readability's sake in the face of this site's code highlighting. It will work as is or without the hashes.
_pgraph() {
sed '/./{H;$!d};x;/'"$1"'/!d'
} <<\DATA
# I have a file with hundreds of paragraphs of
# around 15 lines each. I need to search for a
# pattern, say Occurance: 1. If this pattern is
# found in the para, I need to print the entire
# paragraph. Note that the paragraps are seperared
# by 2 new line characters.
# I have tried the below line of code and this
# obviously prints the first occurence in the
# file. I am somehow unable to use a loop and
# print all such occurances.
# sed -n '1,/Occurance: 1/p' ystdef.txt | tail -9 >
# ystalarm.txt Can I use the g (global) flag with
# sed to make this work? If yes, how?
# Note that I am aware of the grep -A/B/C commands
# but they wont work on my cygwin terminal.
DATA
Now I can do:
_pgraph Note
###OUTPUT
# I have a file with hundreds of paragraphs of
# around 15 lines each. I need to search for a
# pattern, say Occurance: 1. If this pattern is
# found in the para, I need to print the entire
# paragraph. Note that the paragraps are seperared
# by 2 new line characters.
# Note that I am aware of the grep -A/B/C commands
# but they wont work on my cygwin terminal.
Or more specifically:
_pgraph 'Note that I'
# Note that I am aware of the grep -A/B/C commands
# but they wont work on my cygwin terminal.
You can do the same for any file without appending a literal input to the function itself by simply removing everything from <<\DATA
to DATA
in the function definition and running it like:
_pgraph 'PATTERN' </path/to/input.file
awk -vRS= -vORS='\n\n' '/pattern/'
– Stéphane Chazelas Jun 09 '14 at 13:04Unknown option "-RS="
message – Irfan N Jun 09 '14 at 13:34-vRS
, or-v RS
, not-RS
– Stéphane Chazelas Jun 09 '14 at 13:39