For June’s challenge, write a program to read the history of shell commands and determine which ones you use the most.
In bash, you can set the HISTFILE
and HISTFILESIZE
to control history
‘s behavior. To get the commands to count, you can read the right file or shell out to the history
command. From there, you have to decide how to split up each line to figure out what the command is. Can you handle commands with relative paths and absolute paths so you don’t count them separately?
This was an meme for a little while, and I wish I could find my answer to it. If you find my answer, please let me know.
You can see a list of all Challenges and my summaries as well as the programs that I created and put in the Learning Perl Challenges GitHub repository.
With a little help from Perlmonks:
I would use
$ENV{HISTFILE}
instead of"$ENV{HOME}/.bash_history"
but it doesn’t work in cygwin.I didn’t come up with much different, but it’s never too late to add useless features or unnecessary bloat. Let’s allow different sorting and check for shell builtins or customized commands.
At first I set a few variables which can be altered on the command line. Unfortunately I’m not familiar with Pod::Usage yet…
The history file could be named differently or be at a different location. The format of the file could also vary. The default is to assume that the file consists of just lines directly beginning with the command. I’ve seen history files where there is a number first. In such a case giving a position of the command might come in handy.
By default the program displays the 10 most popular commands, but the number can also be changed…
First the history file is parsed line by line creating a hash with each basename of the command as a key with invocation count as a value.
After the whole file has been read and the history hash is complete another hash is created. This time the count is the key and the value is an array of commands.
Before displaying the most popular commands, the amount of keys is checked so that not more elements are sliced than actually existant.
A quick hack over a cup of coffee, so I’ve gone for brevity. Appears to work 🙂
Hi again,
This is my version. Grab the code from pastebin.
I needed aliases transformation and separating “sudo” from other commands, so i made my solution like this:
I’m slightly late to this. I don’t use bash but zsh, so I thought I would write a script for that. Zsh has a completely different format for it’s history, the following is an example:
I ended up using a regex match to extract the actual command, it was quite a nice little exercise.
I am quite the noob at perl, but I have found Brian’s Learning perl to be of excellent help.