Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep multiple patterns and print pattern and its previous lines

Tags:

sed

awk

I have a file with data

cell A
function (A1A2)
Next state
Test cell
Type combinational 
(CO)
output
(A1)
input
(A2)
input
cell X
function ((A1+A2)B)
Hold rising 
Type combinational 
Min_pulse_width
(Z)
output
(A1)
input
(A2)
input
(B)
input

I want output as

cell A
function (A1A2)
Type combinational 
(CO)
output
(A1)
input
(A2)
input
cell X
function ((A1+A2)B)
Type combinational 
(Z)
output
(A1)
input
(A2)
input
(B)
input

The input file has multiple lines above shown format with many parameters present. But from that file I only want to grep cell, function, type, output and its previous line , input and its previous line .

I can grep cell, function, typeusing

grep "cell|function|type" file

and can grep output and its previous line and input And it's previous line as

awk '/input/{print x;print};{x=$0}' file

awk '/output/{print x;print};{x=$0}' file 

But how can I do above 3 steps together and get shown output.

like image 336
Shreya Avatar asked Feb 11 '26 12:02

Shreya


1 Answers

You may try this awk:

awk '/^(in|out)put/{print p; print} /^(cell|function|Type)/; {p = $0}' file

cell A
function (A1A2)
Type combinational
(CO)
output
(A1)
input
(A2)
input
cell X
function ((A1+A2)B)
Type combinational
(Z)
output
(A1)
input
(A2)
input
(B)
input
like image 161
anubhava Avatar answered Feb 17 '26 14:02

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!