Home > database >  How to implement a counter using dictionary in Bash
How to implement a counter using dictionary in Bash

Time:08-28

#!/bin/bash
clear


Counter() {

declare -A dict

while read line; do
    
    if [[ -n "${dict[$line]}" ]]; then
        
        ((${dict[$line]} 1))
        
    else
        
        dict["$line"]=1

    fi

done < /home/$USER/.bash_history

echo ${!dict[@]} ${dict[@]}

}

Counter

I'm trying to write a script that counts the most used commands in your bash history using dictionary to store commands as keys and amount of times you used a command as a value but my code fails successefully.

Can you help me write the code that works.

Python code for reference:

def Counter(file):

    dict = {}

    for line in file.read().splitlines():

        if line not in dict:
            dict[line] = 1
        else:
            dict[line]  = 1

    for k, v in sorted(dict.items(), key=lambda x: x[1]):

        print(f"{k} was used {v} times")


with open("/home/igor/.bash_history") as bash:
    Counter(bash)

Output:

echo $SHELL was used 11 times
sudo apt-get update was used 14 times
ls -l was used 14 times
ldd /opt/pt/bin/PacketTracer7 was used 15 times
zsh was used 17 times
ls was used 26 times

CodePudding user response:

There's no need to initialize the value to 1 for the first occurrence. Bash can do that for you.

The problem is you can't use an empty string as a key, so prepend something and remove it when showing the value.

#! /bin/bash

Counter() {
    declare -A dict

    while read line; do
        c=${dict[x$line]}
        dict[x$line]=$((c 1))
    done < /home/$USER/.bash_history

    for k in "${!dict[@]}" ; do
        echo "${dict[$k]}"$'\t'"${k#x}"
    done

}

Counter | sort -n

CodePudding user response:

Python code for reference:

To count occurrences of lines, in shell you would typically do sort | uniq -c | sort you would do:

sort ~/.bash_history | uniq -c | sort -rn | head
  • Related