Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I get/filter history entries in a specific range?

I have a large history file and frequently use

history | grep somecommand

Now, my memory is pretty bad and I also want to see what else I did around the time I entered the command.

For now I do this: get match, say 4992 somecommand, then I do

history | grep 49[0-9][0-9]

this is usually good enough, but I would much rather do it more precisely, that is see commands from 4972 to 5012, that is 20 commands before and 20 after.

I am wondering if there is an easier way? I suspect, a custom script is in order, but perhaps someone else has done something similar before.

share|improve this question
For history manipulation there are 2 built-ins: – LIttle Ancient Forest Kami Feb 14 '15 at 12:32
up vote 10 down vote accepted

You can tell grep to print some lines surrounding the match, e.g., 3 before and 5 after:

history | grep -B 3 -A 5 somecommand

grep -C 4 is equivalent to grep -A 4 -B 4.

But often you won't know precisely how many lines you want in advance. So use less and search inside it. You can even launch the search from the command line:

history | less +/somecommand
share|improve this answer
very cool trick with less! Didn't know you could do that – warren Oct 4 '10 at 23:22
Very nice, thank you so much! – Aniti Oct 5 '10 at 10:19

try history | grep -C20 '^4992'

share|improve this answer
Thank you, this works! – Aniti Oct 5 '10 at 10:21

Try fc:

fc -l 4972 5012

... it is a bash builtin command. (so don't try it in tcsh :>)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.