【发布时间】: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 中,或者如何在保留最后出现的命令的同时删除重复项。
【问题讨论】: