Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort `.bash_history` by timestamp

Tags:

bash

sorting

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!

like image 275
LukeLR Avatar asked Nov 15 '25 12:11

LukeLR


1 Answers

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/'
}
like image 121
Toby Speight Avatar answered Nov 17 '25 10:11

Toby Speight