Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Most frequent history words



On Apr 25, 12:36pm, Sebastian Gniazdowski wrote:
} Subject: Most frequent history words
}
} Hello,
} can the following be made less coreutils dependent, i.e. more pure-Zsh code?
} 
} print -rl "${historywords[@]}" | sort | uniq -c | sort -k1,1nr -k2,2  | head

It can, but it's probably not very efficient.

The pipe to sort can be replaced with

    print -rl -- ${(o)historywords[@]}

The "uniq -c" would have to be replaced by a loop building a hash whose
keys are words and whose values are the count thereof (making the initial
sort irrelevant).

    typeset -A uniq
    for k in ${historywords[@]}
    do uniq[$k]=$(( ${uniq[$k]:-0} + 1 ))
    done

Some quoting on $k such as ${(b)k} is probably required there, this is
the shakiest part of the process.

Then the final "sort -k..." would have to be done by iterating over the
hash, with "head" just taking an array slice.

    vk=()
    for k v in ${(kv)uniq}
    do vk+="$v=$k"
    done
    print -rl -- ${${${(on)vk}#<->=}[1,10]}

Plus unwrapping there whatever quoting on $k you did in the first loop.



Messages sorted by: Reverse Date, Date, Thread, Author