ire_and_curses
ire_and_curses

Reputation: 70152

How do I select a subset of lines from the history in bash?

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?

Upvotes: 2

Views: 2106

Answers (6)

Kim Stebel
Kim Stebel

Reputation: 42047

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.

Upvotes: 4

Susheel Javadi
Susheel Javadi

Reputation: 3084

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.

Upvotes: 2

PanCrit
PanCrit

Reputation: 2718

I type
history | grep " 840"

Upvotes: 1

Ryan Bright
Ryan Bright

Reputation: 3565

grep's -C option provides context. Try:

$ history | grep -C 5 ifconfig

Upvotes: 5

Joachim Sauer
Joachim Sauer

Reputation: 308031

history | grep -C 5 ifconfig

Upvotes: 4

dfa
dfa

Reputation: 116334

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

Upvotes: 1

Related Questions