2

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?

2
  • 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. Commented Sep 7, 2010 at 7:22
  • You need to press check marks next to anwsers you want to accept. Commented Sep 7, 2010 at 7:22

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

Comments

0

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.

1 Comment

You should upvote (press the upwards pointing arrow) those answers which you find useful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.