2

My history is 'polluted' with some specific lines that have typo's and such. For example: I often have to ssh to a certain server like so:

ssh foo-bar@domain.tld
> Connects succesfully

But I also make a typo sometimes:

ssh bar-foo@domain.tld
> Permission denied

Because I rely on history this typo is duplicated multiple times:

cat .zsh_history | grep bar-foo@domain.tld
> : 1510301683:0;ssh bar-foo@domain.tld
> : 1511166682:0;ssh bar-foo@domain.tld
> : 1511193552:0;ssh bar-foo@domain.tld
> : 1512730972:0;ssh bar-foo@domain.tld
> : 1516368993:0;ssh bar-foo@domain.tld
> : 1516802690:0;ssh bar-foo@domain.tld
> : 1519633368:0;ssh bar-foo@domain.tld

Is there an easy way to clean up my history purely by the results of the grep-command? (or perhaps there's some other, more clever solution?)

Update:

Please note: I am not looking for a way to delete line x from the history; I know there are plenty of articles out there that cover that. I'm simply looking for a (simple?) way to delete all lines that contain string y.

Giel Berkers
  • 2,389

2 Answers2

1

This function will remove any one line you want from your Zsh history, no questions asked:

# Accepts one history line number as argument.
# Alternatively, you can do `dc -1` to remove the last line.
dc () {
  # Prevent the specified history line from being saved.
  local HISTORY_IGNORE="${(b)$(fc -ln $1 $1)}"

Write out the history to file, excluding lines that match $HISTORY_IGNORE.

fc -W

Dispose of the current history and read the new history from file.

fc -p $HISTFILE $HISTSIZE $SAVEHIST

TA-DA!

print "Deleted '$HISTORY_IGNORE' from history." }

If you want to additionally prevent all dc commands from being written to history, add the following in your ~/.zshrc file:

zshaddhistory() {
 [[ $1 != 'dc '* ]]
}

Alternatively, for a more comprehensive solution, try my Zsh Edit plugin.

0

You can use this command to delete properly all lines with the string in the history :

sed -i '/string/d' .bash_history