views:

149

answers:

6

Quite often I grep through my bash shell history to find old commands, filepaths, etc. Having identified the history number of interest, I would like to see a few lines of context on either side, i.e. view a subset of history lines. For example:

$ history | grep ifconfig

8408  ifconfig eth0
8572  sudo ifconfig eth0 down

I would like to look at the 5 lines or so either side of line 8572. Obviously knowing the line number I can page through the history with less, but this seems very stupid. As far as I can tell, the manpage doesn't seem to have this information either.

Is there a simple way to retrieve arbitrary lines of history in bash?

+1  A: 

type ctrl-r, then some characters (interactive searching). More information here.

dfa
+4  A: 
history | grep -C 5 ifconfig
Joachim Sauer
+4  A: 

grep's -C option provides context. Try:

$ history | grep -C 5 ifconfig
Ryan Bright
+1  A: 

I type
history | grep " 840"

PanCrit
+1  A: 
history | grep ifconfig -A5 -B5

A = number of lines after the match found by grep B = number of lines before the match found by grep You can also change the number of lines from 5 to any number you want.

Bart J
+2  A: 

If you only want to see it for specific line numbers, you can also use something like this

history | head -n 120 | tail -n 5

The example prints lines 116 through 120.

Kim