I've enabled the timestamp for my .bash_history by using the HISTTIMEFORMAT="%d.%m.%y %T " instructive in .bashrc. However, sometimes the order of the entries in the .bash_history is messed up, and I want to sort that file by the timestamp. Unfortunately, the timestamp is not in the same line as the entry, but one line above, like this:
#1512649029
a command
#1512649032
another command
#1512649039
a third command
So how can I sort the file by these "pairs" of lines? Furthermore, there are entries that have no timestamps, e.g. lines that have no #... line above. I want these lines to gather at the top of the file. Thanks!
We can use a simple sed program to join lines:
/^$/d # skip blank lines
/^#/N # append next line to timestamp
/^#/!s/^/#0\n/ # command without timestamp - prefix with #0
s/#// # remove initial #
y/\n/ / # convert newline to space
and another to restore the timestamp comments:
s/(\S+) /#\1\n/
Putting that all together, we get
sort_history() {
sed -e '/^$/d' -e '/^#/N' -e '/^#/!s/^/#0\n/' \
-e 's/#//' -e 'y/\n/ /' <<<"$in" \
| sort -n | sed -e 's/\(\S\+\) /#\1\n/'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With