【问题标题】:Delete duplicate commands of zsh_history keeping last occurence删除 zsh_history 的重复命令,保留最后一次出现
【发布时间】:2022-11-19 19:12:00
【问题描述】:

我正在尝试编写一个 shell 脚本,从我的 zsh_history 文件中删除重复的命令。没有真正的 shell 脚本经验并且鉴于我的 C 背景,我写了这个似乎有效的怪物(虽然只在 Mac 上),但需要几个生命才能结束:

#!/bin/sh

history=./.zsh_history
currentLines=$(grep -c '^' $history)
wordToBeSearched=""
currentWord=""
contrastor=0
searchdex=""

echo "Currently handling a grand total of: $currentLines lines. Please stand by..."
while (( $currentLines - $contrastor > 0 ))
do
    searchdex=1
    wordToBeSearched=$(awk "NR==$currentLines - $contrastor" $history | cut -d ";" -f 2)
    echo "$wordToBeSearched A BUSCAR"
    while (( $currentLines - $contrastor - $searchdex > 0 ))
    do
        currentWord=$(awk "NR==$currentLines - $contrastor - $searchdex" $history | cut -d ";" -f 2)
        echo $currentWord
        if test "$currentWord" == "$wordToBeSearched"
        then
            sed -i .bak "$((currentLines - $contrastor - $searchdex)) d" $history
            currentLines=$(grep -c '^' $history)
            echo "Line deleted. New number of lines: $currentLines"
            let "searchdex--"
        fi
        let "searchdex++"
    done
    let "contrastor++"
done

^这是任何人都不应该使用的可怕代码^

我现在正在寻找一种使用更多类似 shell 的约定的耗时更少的方法,此时主要是 sed。事实是,zsh_history 以一种非常特殊的方式存储命令:

: 1652789298:0;man sed

命令本身总是以“:0;”开头。 我想找到一种方法来删除重复的命令,同时保持每个命令的最后一次出现完整且有序。

目前我正处于一个功能行的位置,该行将删除进入文件的奇怪行(换行符等):

#sed -i '/^:/!d' $history

但仅此而已。不太确定如何让表达式在 sed 中查找而不回落到永恒的 while 中,或者如何在保留最后出现的命令的同时删除重复项。

【问题讨论】:

    标签: bash shell zsh


    【解决方案1】:

    zsh 选项 hist_ignore_all_dups 应该做你想做的。只需将 setopt hist_ignore_all_dups 添加到您的 zshrc。

    【讨论】:

    • 我已经有了(似乎不起作用但确实存在),我想删除文件中当前的重复项
    • 你有设置inc_append_history吗?可能是这个问题:github.com/ohmyzsh/ohmyzsh/issues/9359
    • 我没有它,只是尝试了它,但它仍然不起作用。但这不是我在这里要找的,如前所述,我想删除文件的重复项
    • 与 OP 问题无关,该问题说明如何从当前文件中删除重复项。修改 .zshrc 只是为了防止这种情况在未来发生,而且这个问题也无关紧要......
    【解决方案2】:

    我想要类似的东西,但我不关心保留你提到的最后一个。这只是查找重复项并删除它们。

    我使用了这个命令,然后删除了我的.zsh_history并将其替换为这个命令输出的.zhistory

    所以从你的主文件夹:

    cat -n .zsh_history | sort -t ';' -uk2 | sort -nk1 | cut -f2- > .zhistory
    

    这将有效地为您提供包含更改列表的文件.zhistory,在我的例子中,它从 9000 行变为 3000 行,您可以使用 wc -l .zhistory 检查它以计算它的行​​数。

    在对它进行任何操作之前,请仔细检查并备份您的 zsh 历史记录。

    可以修改排序命令以按数值对其进行排序并以某种方式实现您想要的内容,但您将不得不进一步调查。

    我找到了脚本here,以及一些避免将来保存重复项的命令

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 2016-09-10
      • 2022-11-22
      • 2022-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多