Grep multiple patterns and print pattern and its previous lines

Viewed 69

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.

3 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
grep -Ev '(Next state)|(Test cell)|(Hold rising)|(Min_pulse_width)' file

Use -E to enable regular expressions and -v for inverse searching. Then state the terms you DON'T want to search for.

This might work for you (GNU sed):

sed -nE 'N;/^(cell|function|Type)/P;/\n(output|input)/p;D' file

Turn off implicit printing -n and on easier regexp -E.

Open a two line window.

Print the required strings using pattern matching.

Delete everything and repeat.

Related