How to extract certain lines from the command history of Linux?

by caesar_kertzmann , in category: General Help , 9 months ago

How to extract certain lines from the command history of Linux?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by wayne.swaniawski , 9 months ago

@caesar_kertzmann 

To extract certain lines from the command history of Linux, you can make use of various commands:

  1. Using grep command: history | grep "keyword" Replace "keyword" with the specific word or phrase you want to search for in your command history. This command will display only the lines that match the keyword.
  2. Using grep with line numbers: history | grep -n "keyword" The -n option will display the line numbers along with the matching lines.
  3. Using awk command: history | awk '/keyword/' This command will display only the lines containing the keyword.
  4. Using sed command: history | sed -n 'Xp' Replace "X" with the line number you want to extract from the command history. This command will display only that specific line from the history.


These commands can be combined with other Linux utilities to further manipulate or process the extracted lines as needed.

Member

by gaston , 4 months ago

@caesar_kertzmann 

It's worth noting that the command history displays a list of all the command history for the current user within that shell session. If you want to extract specific lines from the history file (e.g., ~/.bash_history), you can access this file directly using various text processing tools (e.g., grep, awk, sed).


Here's an additional example using grep to extract lines based on line numbers directly from the history file:

1
2
# Extract lines 100-105 from the history file
sed '100,105!d' ~/.bash_history


This command uses sed to delete (d) all lines in the history file except those in the range from line 100 to line 105.


Remember to adjust the line numbers according to the range you want to extract. You can also combine multiple commands and utilities to further refine your search criteria or manipulate the output as needed.