h1

grep’ing for some text + next few lines..

11/01/2011

Was interesting in search output for a particular piece of text, and then getting that line plus the next couple of lines. Google to the rescue again. Found this article on Linux Questions. grep has a (-A/-B/-C) parameter that I never used before. Works well if you do not mind multiple lines being separated by — lines. As per the article, you could also use ‘sed’ in the form of

sed -n ‘/text-to-look-for/,+1p’ file.txt >newfile.txt

I tried both but the grep command was easiest to recall in a pinch. The sed one works better and you do not need to pipe the output to another grep to remove the — lines (grep -v “^–$”)

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.