I would like to delete all history entries matching a certain string. I found this method:

grep -v searchstring "$HISTFILE" > /tmp/history
mv /tmp/history "$HISTFILE"

but it does not account for the HISTTIMEFORMAT comments, for example:

echo 1
echo 2
echo 3

If I wanted to remove "echo 2", the preceding comment would need to be removed as well. How can I do this?


Sed is your friend (awk could do it as well), you may use this code (assuming every line matched indeed has a time line):

sed '$!N;/echo 2/!P;D' "$HISTFILE" > /tmp/history

or to do it directly in the history file:

sed -i '$!N;/echo 2/!P;D' "$HISTFILE"

The example you have will become this:

echo 1
echo 3

A more restrictive match: only erase actual time lines before the pattern (match lines that have one field that is a # followed by ten digits)

awk -vp="echo 2" ' {b=$0};b~p{next}
                   NF=1 && b~/#[0-9]{10}/{a=b;next}
                   {print(a RS b)}
                 ' "$HISTFILE"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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