Grep pattern only and surrounding lines

Hello,

I am trying to grep search a pattern and a line before it.

cat input
>record1
hello1hello2hellonhello3
>record2
helloohello1hello2hello3

When I use, grep with -o option and either of -A/B/C options, I still can't see lines before or after the pattern. But the exact pattern is being printed fine though. Any pointers are appreciated.

Expected output is

cat input | grep -o "hello[a-z]hello"
>record1
hellonhello
>record2
helloohello

But current output is

cat input | grep -o -B 1 "hello[a-z]hello"
hellonhello
helloohello

Thanks in advance.

-o and -B are mutually exclusive, -o tells it to show nothing but the matching text. Remove -o.

1 Like

Thank you @Corona688. I had that doubt in mind.

But I would like to see only the pattern and the line before it. Can you please share any comments?

sed 's/.*\(hello[a-z]hello\).*/\1/' infile
1 Like

grep doesn't do that, you can use awk:

awk 'match($0,/hello[a-z]hello/) { print L ; print substr($0,RSTART,RLENGTH); } ; { L=$0 }' input
1 Like

Amazing! Thank you!

1 Like