0

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:

#1517681911
echo 1
#1517681918
echo 2
#1517681931
echo 3

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

1

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:

#1517681911
echo 1
#1517681931
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.