如何删除历史记录中匹配给定字符串的命令?

lin*_*fix 16 bash command-history xargs text-processing

我需要删除历史记录中匹配字符串的所有命令。我试过了:

$ history | grep searchstring | cut -d" " -f2 | history -d
-bash: history: -d: option requires an argument

$ history | grep searchstring | cut -d" " -f2 | xargs history -d
xargs: history: No such file or directory

$ temparg() { while read i; do "$@" "$i"; done }
$ history | grep searchstring | cut -d" " -f2 | temparg history -d
(no error, but nothing is deleted)
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?

Mic*_*zek 22

history命令仅对您的历史文件进行操作$HISTFILE(通常为~/.history~/.bash_history)。如果您只是从该文件中删除行会容易得多,这可以通过多种方式完成。grep是一种方法,但您必须小心不要在仍在读取文件时覆盖文件:

$ grep -v searchstring "$HISTFILE" > /tmp/history
$ mv /tmp/history "$HISTFILE"
Run Code Online (Sandbox Code Playgroud)

另一种方法是sed

$ sed -i '/searchstring/d' "$HISTFILE"
Run Code Online (Sandbox Code Playgroud)


Chr*_*own 11

如果您不关心从当前会话中删除命令,Michael Mrozek 的回答会起作用。如果这样做,您应该在执行他的帖子中的操作之前通过执行history -a.

此外,从历史文件中删除所需的条目后,您可以通过发出history -c、然后history -r.


the*_*gix 7

对于那些寻找单线的人:

while history -d $(history | grep 'SEARCH_STRING_GOES_HERE'| head -n 1 | awk {'print $1'}) ; do :; history -w; done
Run Code Online (Sandbox Code Playgroud)

所以,如果你想例如。删除包含密码的多行,只需将“SEARCH_STRING_GOES_HERE”替换为密码即可。这将在您的整个历史记录中搜索该搜索字符串并将其删除。

需要注意的2件事

  • grep 使用正则表达式,除非您提供 -F 作为参数
  • 一旦没有更多匹配项,该命令将显示 1 个错误。忽略它。

  • 它连续运行删除命令,直到它因错误而失败(因为没有更多内容可删除)。只需忽略该错误即可。 (2认同)