4

I use the command history | grep <key_word> to look for all the commands in the history with that specific key_word. That's great but sometimes not enough: I would love to see the N commands before and the M commands after each result.

For example with history | grep build, I want to see the N=10 commands before and the M=5 commands after each result. Targeting the following ideal output:

 1209  git status
 1210  git add .
 1211  git commit -m 'bla bla bla'
 1212  git push http://xxx.xxx.xx.x:xxxxx/
 1213  git tag 
 1214  source tools/settings.sh 
 1215  cd demos/xxxxxxx/
 1216  xxxxxxx 
 1217  cd demos/wait_zcu102/
 1218  ls
 1219  cd build.sw/      <------------------------------------- <key_word> is here
 1220  ls
 1221  atom .
 1222  source tools/settings.sh 
 1223  cd demos/xxxxxxxxx/
 1224  xxxxx 

Is there a way to do this?

Leos313
  • 3,729
  • 4
  • 29
  • 61

2 Answers2

4

There is a native support for what you are asking:

  • grep -B 1 <key_word> displays one line [B]efore each match
  • grep -A 1 <key_word> displays one line [A]fter each match

Both options can be used at the same time, and obviously you can specify any number >= 0.

To complete your example: history | grep -B 10 -A 5 build

For more information, look at the Context Line Control section from the grep man.

aymericbeaumet
  • 5,464
  • 1
  • 32
  • 48
1

From the documentation for grep:

 -A num, --after-context=num
         Print num lines of trailing context after each match.

 -B num, --before-context=num
         Print num lines of leading context before each match.

 -C[num, --context=num]
         Print num lines of leading and trailing context surrounding each match. The default is 2 and is equivalent to -A 2 -B 2.

In your example above, you could use:

history | grep -A5 -B10 build
Tom Lord
  • 22,829
  • 4
  • 43
  • 67