如何从特定时间段删除命令行历史记录?

如何在特定时间段内删除命令行历史记录?

只用一个命令就可以这样做吗?

虽然可以存储运行命令的时间,但历史操作命令不使用时间作为参考。 在man bash查找HISTTIMEFORMAT

 HISTTIMEFORMAT If this variable is set and not null, its value is used as a format string for strftime(3) to print the time stamp associated with each history entry displayed by the history builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines. 

如果在运行要删除的命令之前设置了HISTTIMEFORMAT ,则.bash_history将包含如下行:

 $ tail -4 ~/.bash_history #1449955320 history #1449955329 history -w 

然后你可以利用Unix时间戳来删除它们,使用awk ,例如:

 awk -F# -v end=$(date -d yesterday +%s) \ -v start=$(date -d 'now - 3 days' +%s) \ '$2 < start || $2 > end {print; getline; print}' 

我不确定此命令如何与多行命令一起使用,但您可以计算时间戳以获取分配给命令的编号,然后使用history将其删除。


如果您事先没有设置HISTTIMEFORMAT ,那么您必须手动执行此操作。