我正在尝试编写一个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的约定的更少的生命消耗方法,主要是在这一点上。问题是,zsh_history以非常特殊的方式存储命令:
: 1652789298:0;man sed在命令本身之前总是有":0;“。我想找到一种方法来删除重复的命令,同时保持每个命令的最后出现保持原样和顺序。
目前,我已经有了一个函数行,它将删除进入文件中的奇怪行(newline等等):
#sed -i '/^:/!d' $history但仅此而已。不太清楚如何使表达式在不陷入永恒的情况下查找sed,也不知道如何在保留最后出现的命令的同时删除重复的表达式。
发布于 2022-05-18 18:05:16
zsh选项hist_ignore_all_dups应该做您想做的事情。只需将setopt hist_ignore_all_dups添加到zshrc中即可。
发布于 2022-11-19 10:27:44
我想要类似的东西,但我不关心保存最后一个,正如你提到的。这只是找到副本并移除它们。
我使用了这个命令,然后删除了我的.zsh_history,用这个命令输出的.zhistory替换它。
所以在你的主文件夹里:
cat -n .zsh_history | sort -t ';' -uk2 | sort -nk1 | cut -f2- > .zhistory这将有效地为您提供包含更改列表的文件.zhistory,在我的示例中,从9000行到3000行,您可以使用wc -l .zhistory检查它的行数。
在做任何事情之前,请反复检查并备份您的zsh历史记录。
排序命令可能会被修改,以便按数值对其进行排序,并以某种方式将所需的内容存档,但您必须对此进行进一步研究。
我找到了脚本这里,以及一些避免将来保存副本的命令。
https://stackoverflow.com/questions/72293670
复制相似问题