Printing previous line based on pattern using sed

Hi,

I have a written a shell script to get the previous line based on the pattern.

For example if a file has below lines:

----------------------------------------------
#UNBLOCK_As _per
#As per
205.162.42.92
 
#BLOCK_As_per
#-----------------------
#input checks
abc.com
google.com
121.223.213.99
 
#BLOCK_As_per
#-----------------------
#output checks
12.91.77.123
200.55.185.74
 
----------------------------------------------

I want to get the line of a pattern I am searching for along with the previous lines also based on pattern only.

From the above lines:
If I am searching for pattern "200.55.185.74" I want this pattern to be printed along with the "#output" and "#BLOCK" lines.

I am able to get the output what I want but few times for few patterns script is not able to process it.

I am using sed command. Below code is working for all the patterns but when I am trying to search "200.55.185.74" its getting previous line "#output checks" but its not printing "#BLOCK_As_per" line.

I want the output in the below manner "

#BLOCK_As_per
#output checks
200.55.185.74

Below is code:
-------------------------------

read -r heu
 
net=$(echo "$heu" | sed 's/[]\[:?+*/^\$!|.]/\\&/g')
 
$(sed -n -e '
/^#[_,BLOCK,UNBLOCK,root, Ineffective]/h
/^#[As,output,input]/ {
H
g
d
}
/'"$net"'/ {
H
g
p
}' file)

Please help me... should I use branching in sed. If yes them please tell me how to use it.

appreciate your help....

Here is a quick solution, I think the sections are seperated by a blank line, so set the RS=""; FS="\n"

#!/bin/ksh
read -r heu
awk -v heu=${heu} 'BEGIN{RS=""; FS="\n"}
{
        if(match($0, heu)) {print $0}
}' FILENAME

Should work, let me know.

I worked hard to get the output with the help of sed. So, please write the code in sed only. Also, its not complusion that the lines are separated with blank line. Some times lines are separated with blank lines or some times lines are not separated with blank lines...

Also, when i try to execute your code I am getting below error.

awk: syntax error near line 1
awk: bailing out near line 1

Please help...

hello why not. this simple thing.

grep -B m -A n 'pattern' infile

m= number of lines you want before the pattern.
n= number of lines you want after the pattern.

Regards

Actually lines are not fixed they change. If the lines are fixed then I can use the command given by you.

please tell me any other solution.

You almost got it. Just change the two regexs from

/^#[_,BLOCK,UNBLOCK,root, Ineffective]/
/^#[As,output,input]/ 

to

/^#\(_\|BLOCK\|UNBLOCK\|root\|Ineffective\)/
/^#\(As\|output\|input\)/

Although the "g" in

H
g
d

is not necessary.