LoginSignup
0
0

More than 5 years have passed since last update.

【Python】.zsh_historyの履歴のタイムスタンプを削除

Last updated at Posted at 2017-10-12

はじめに

history.png

pecoなどに利用される .zsh_historyの履歴にはタイムスタンプが押されます。
: 1507713777:0;みたいなやつです。
これはzplugの機能によるものなので、zplugを入れてない人に表示されません。
修正
zplugによるものではなく、.zshrcに書いてあるsetopt EXTENDED_HISTORYによるものです。

で、今回はこのタイムスタンプを消し去りたいと思いました。
何故なら、同じ内容がたくさん書かれていてキモいからという個人的な理由です。

実装

環境

  • python 3.6.0

コード

arrange_zsh_history.py
import subprocess
import re

contents = subprocess.check_output('cat .zsh_history', shell=True)
data_list_b = contents.splitlines()
s = r': [0-9]{10}:[0-9];'
data_list = [repr(l).lstrip('b').strip('\'') for l in data_list_b]

result_set = set([re.sub(s, '', d) for d in data_list])
f = open('.zsh_history', 'w')
for r in list(result_set):
    if r != '':
        p = re.compile(r'\\+')
        r = p.sub(r'\\', r)
        if r[0] == '\"':
            r = r.strip('\"')
        f.write(r+'\n')
f.close()



コードはこんな感じです。
.zsh_historyarrange_zsh_history.pyを同じ階層に置いて、

python arrange_zsh_history.py

を実行すれば.zsh_historyの中身が書き換わります。

コードの説明

このコードは.zsh_historyの中身を取ってきて、内容を編集した上で.zsh_historyに上書きするコードです。
その際に

r': [0-9]{10}:[0-9];'

の正規表現にマッチしたタイムスタンプの文字列を

set([re.sub(s, '', d) for d in data_list])`

によって変換しています。
この時、\nなどバックスラッシュを含めた文字列が\\nのような形に変換されてしまうので、

p = re.compile(r'\\+')
r = p.sub(r'\\', r)

の処理を行い、任意の数の\を一つに変換しています。

おわりに

本当は.zsh_historyの中身を取得するのに

contents = open('.zsh_history', 'r')

のようにして取得したかったのですが、上手くいかず(多分エンコーディングのせい??)泣く泣く

contents = subprocess.check_output('cat .zsh_history', shell=True)

のように強引に取得しました。Pythonもっと勉強しなくては...
もし、「こっちの方がいいよ!」「こっちの方がクレバーだぜ!」という意見をくれる方がいらっしゃったらコメントを頂けると助かります。

0
0
2

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
0