LoginSignup
0
1

More than 5 years have passed since last update.

zshのextended history fileをマージする

Last updated at Posted at 2017-01-07

Dropboxでzshの履歴を管理していると、confilicted copyができることがある。

しかし、zshのextended_historyオプションを有効にしてあれば、historyファイルは以下のように実行時の時刻が記録される。(参照:zshのマニュアル)

: 1483789382:0;cd ~/Dropbox
#:(実行時のunix time):(実行時間);(コマンド)

そこで、時刻順にextended historyファイルをマージするスクリプトを書いたのでおいておく。

#!/usr/bin/env python3

# License: MIT

import argparse
import re
import sys

parser = argparse.ArgumentParser(description='merge')
parser.add_argument('files', metavar='file', nargs='+', help='zsh extended history files')
args = parser.parse_args()

p = re.compile(b':([ 0-9]*):([0-9]+);(.*)', re.S)
def get_lines(fp):
        histories = set()
        i = iter(fp.readlines())
        for line in i:
                date, time, command = p.match(line).groups()
                date = int(date)

                while len(command)>1 and command[-2] == b'\\'[0]:
                        command += next(i)
                histories.add((date, time, command))
        return histories

histories = set()
for f in args.files:
        with open(f, 'rb') as fp:
                histories.update(get_lines(fp))

for date,time,command in sorted(histories, key=lambda r: r[0]):
        print(":{:11}:".format(date), end="")
        sys.stdout.flush()
        sys.stdout.buffer.write(time)
        sys.stdout.buffer.write(';')
        sys.stdout.buffer.write(command)

使い方はこんな感じ

./merge .zsh_history *.zsh_history >merged_history
mv merged_history > .zsh_history

追記:
偉大なる先駆者の存在を忘却していました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1