gpt4 book ai didi

bash - 概括 awk 函数

转载 作者:行者123 更新时间:2023-11-29 09:29:20 25 4
gpt4 key购买 nike

为了提高工作效率,我使用以下函数来了解我必须为哪些函数设置别名,因为我最常使用它们:

function mu() {
if [[ $# -eq 0 ]]; then
history | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10
elif [[ $# -eq 1 ]]; then
history | awk '$2=="'$1'"{CMD[$3]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10
elif [[ $# -eq 2 ]]; then
history | awk '$2=="'$1'"&&$3=="'$2'"{CMD[$4]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10
fi
}

此函数使用 0、1 或 2 个参数,在函数作为输入的参数之后显示最常用的参数。

有没有办法让它适用于任意数量的参数?

对于 4 个和 5 个参数,命令应该如下所示:

history | awk '$2=="'$1'"&&$3=="'$2'"&&$4=="'$3'"{CMD[$5]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl |  head -n10
history | awk '$2=="'$1'"&&$3=="'$2'"&&$4=="'$3'"&&$5=="'$4'"{CMD[$6]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10

基本上,每个参数都应该添加另一个条件,例如 &&$4=="'$3'" 并在 [$6] 之后更改括号内的数字。

这是预期的输出:

mu
1 1065 13,3861% cd
2 1007 12,6571% ls
3 761 9,56511% vim
4 755 9,48969% docker-compose
...

mu ls
1 823 81,7279%
2 12 1,19166% logs
3 5 0,496524% mnt
...

等等。

最佳答案

你可以这样做:

function mu() {
history | awk -v input="$@" -v pos="$((2 + $#))" '( substr($0, index($0,$2)) ~ "^" input){CMD[$pos]++;count++} END{ for (a in CMD) print CMD[a] " " CMD[a]/count*100 "% " a}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10
}

这里,繁重的工作由 -v input="$@"-v pos="$((2 + $#))"( substr($0, index($0,$2)) ~ "^"input) :我们将参数数组转换为字符串 input。然后我们将它与我们的历史命令的开头进行比较。如果匹配,我们使用 pos 变量来确定要显示的字段。

旁注:对于 zsh,只需替换 pos="$((4 + $#))"index ($0,$4) 以获得相同的结果。

关于bash - 概括 awk 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49491160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com