anshul gupta anshul gupta - 5 years ago 290
Bash Question

How to print a line above the one with matching pattern in shell?

I want to print line 1 when the pattern match in line 2. For example -

this is line 1 without pattern
this is line 2 with random pattern

When I do grep on "random", I want to print "this is line 1 without pattern"?
Any easy trick with grep?

Answer Source

Use grep with a before context to find your match and the line before it like this:

grep -B1 "random" file

then use an inverted grep to suppress the lines containing your matches so you are left with just the preceding lines:

grep -B1 "random" file | grep -v "random"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download