Match string and print preceding line

Text processing is fun. Well, fun if you like to beat your head against a wall. Most of the time I just string a few things together to get whatever I am doing done. Its much better to find the shortest way to do something, it spawns less processes, is more efficient and generally a good idea. So if you have ever wanted to match a string from some given output and only print the preceding line here you go.

awk '/pattern/{print x};{x=$0}'

You might also wonder why you might want to do that. Well the reason I wanted to do it was to pull the sar output of the last run. Sar output ends in ^Average: but I just wanted the line before that so this is what I came up with.

sar | awk '/^Average:/{print x};{x=$0}'

That just spits out the last recorded sar information like this.

03:40:01 PM all 31.88 0.14 3.72 0.65 63.61

Great for using in scripts to collect bits of information you might need.

Oh and for good measure if I wanted to do this before I would have done this.

sar | grep -B1 ^Average: | grep -v ^Average

And look at how much time I saved by not having the extra pipe!

$ time sar | grep -B1 ^Average: | grep -v ^Average
03:50:01 PM all 28.88 0.14 3.39 0.54 67.06

real 0m0.008s
user 0m0.010s
sys 0m0.000s


time sar | awk '/^Average/{print x};{x=$0}'
03:50:01 PM all 28.88 0.14 3.39 0.54 67.06

real 0m0.007s
user 0m0.000s
sys 0m0.010s

No Comments

Leave a Reply

Your email is never shared.Required fields are marked *

To submit your comment, click the image below where it asks you to...
Clickcha - The One-Click Captcha