tags:

views:

43

answers:

3

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?

+1  A: 

http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files

wRAR
Thank you.... !!
Khushboo
A: 

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 XY and cd .. the same), normalize the lines by removing the command arguments after the space; split
  • sort the sums and print out the command with the highest sum.
poke
thank u.. was useful
Khushboo
You should upvote (press the upwards pointing arrow) those answers which you find useful.
poke
A: 

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.

slomojo
Reading the full text and splitting it with regular expressions is quite overkill.. Python can read files line by line..
poke
@poke... frankly, doing this in python instead of bash scripting is pretty much overkill.
slomojo