根据迈克尔和克里斯的回答,我提出了以下建议。将其添加到~/.bashrc
文件中,然后使用. ~/.bashrc
或加载它source ~/.bashrc
。
:<<COMMENT
Deletes all lines from the history that match a search string, with a
prompt. The history file is then reloaded into memory.
Examples
hxf "rm -rf"
hxf ^source
See:
- https://unix.stackexchange.com/questions/57924/how-to-delete-commands-in-history-matching-a-given-string
COMMENT
#The unalias prevents odd errors when calling". ~/.bashrc" (May result in
#"not found" errors. That's okay).
unalias hxf
hxf() {
read -r -p "About to delete all items from history that match \"$1\". Are you sure? [y/N] " response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y)$ ]]
then
#Delete all matched items from the file, and duplicate it to a temp
#location.
echo -e "grep -v \"$1\" \"$HISTFILE\" > /tmp/history"
grep -v "$1" "$HISTFILE" > /tmp/history
#Clear all items in the current sessions history (in memory). This
#empties out $HISTFILE.
echo "history -c"
history -c
#Overwrite the actual history file with the temp one.
echo -e "mv /tmp/history \"$HISTFILE\""
mv /tmp/history "$HISTFILE"
#Now reload it.
echo -e "history -r \"$HISTFILE\""
history -r "$HISTFILE" #Alternative: exec bash
else
echo "Cancelled."
fi
}
history -d X
。我碰到了这个问题,因为我刚刚做了history | grep search_str | sort -nr | awk '{print $1}' | while read i; do history -d $i; done
。没有错误,但没有删除任何内容。有人可以解释为什么吗?