I want to write a python script which reads the '.bash_history' file and prints the statistics. Also, I would like to print the command which was used the most. I was able to read the bash history through the terminal but I'm not able to do it through python programming. Can someone please help me with how to start with it?
-
against each answer to each of your questions there is a "tick mark" icon. Click on it and it turns green. Select the answer you find most useful for each question and click on this icon.Manoj Govindan– Manoj Govindan2010-09-07 07:22:20 +00:00Commented Sep 7, 2010 at 7:22
-
You need to press check marks next to anwsers you want to accept.wRAR– wRAR2010-09-07 07:22:44 +00:00Commented Sep 7, 2010 at 7:22
Add a comment
|
3 Answers
Something beginning with...
#!/usr/bin/env python
import os
homedir = os.path.expanduser('~')
bash_history = open(homedir+"/.bash_history", 'r')
Now we have the file open... what operations do you want to do now?
Print the contents of the file.
bash_history_text = bash_history.read()
print bash_history_text
Turn the string into an array of lines...
import re
splitter = re.compile(r'\n')
bash_history_array = splitter.split(bash_history_text)
Now you can do array sorting, filtering etc. to your hearts content.
Just some basic ideas, with important python functions for that:
- read the file;
open - go through all lines and sum up the number of occurences of a line;
for,dict - in case you only want to check parts of a command (for example treat
cd XYandcd ..the same), normalize the lines by removing the command arguments after the space;split sortthe sums andprintout the command with the highest sum.
1 Comment
poke
You should upvote (press the upwards pointing arrow) those answers which you find useful.