Required 3 lines above the file and below file when string matches

i had requirement like i need to get "error" line of above 3 and below 3 from a file .I tried with the below script.But it's not working.

 
y='grep -n -i error /home/file.txt|cut -c1'
echo $y
head -$y /home/file.txt| tail -3 >tmp.txt
tail -$y /home/file.txt head -3 >>tmp.txt

Check out the -B and -A options of man grep (linux).

If

grep -A3 -B3 -i error /home/file.txt

doesn't work on your system, mayhap

tail -n +$(($(grep -ni error /home/file.txt | cut -d: -f1)-3)) /home/file.txt | head -7

does?

If your grep doesn't support the -A and the -B options you can try:

awk 'NR==FNR{if($0 ~ /error/){n=NR}next}FNR > n-4 && FNR < n+4' /home/file.txt /home/file.txt
2 Likes

Thanks to all for your suggestions and Franklin52 code worked for me...