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?)


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.

  • Possible duplicate of Remove a certain line from Bash history file – agc Apr 24 '18 at 7:26
  • Not sure if it's a duplicate. I just want to clean my history by deleting all lines that contain string x. The linked question is how to delete by line numbers. – Giel Berkers Apr 24 '18 at 8:33
  • You might be interested in zsh's option HIST_IGNORE_ALL_DUPS in order to not stor duplicates in your history at all: If a new command line being added to the history list duplicates an older one, the older command is removed from the list (even if it is not the previous event). – mpy Apr 24 '18 at 16:36
  • @GielBerkers, Remove a certain line from Bash history file seems quite general, with answers using various methods. The simplest grep fix is in a comment by *mivk, which prints out the needed commands, (without actually running them): history | grep XYZ | grep -v grep | tac | awk '{print "history -d", $1}' – agc Apr 25 '18 at 0:59

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

sed -i '/string/d' .bash_history

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.