Skip to content

Instantly share code, notes, and snippets.

@dvdbng
Created December 21, 2016 18:02
Show Gist options
  • Save dvdbng/e08ce5ba50f224b59c9fe2a91fdcea61 to your computer and use it in GitHub Desktop.
Save dvdbng/e08ce5ba50f224b59c9fe2a91fdcea61 to your computer and use it in GitHub Desktop.
Migrate zsh history to fish
import os
import re
def zsh_to_fish(cmd):
return (cmd.replace('&&', '; and ')
.replace('||', '; or '))
def is_valid_fish(cmd):
for reg in r'^\S+=', r'\$\(', r'\[ ', r'`', r'\\$':
if re.match(reg, cmd):
return False
return True
with open(os.path.expanduser('~/.local/share/fish/fish_history'), 'a') as o:
with open(os.path.expanduser('~/.zsh_history')) as f:
for line in f:
line = line.strip()
if line and re.match('^:\s+\d+:\d;', line):
meta, command = line.split(';', 1)
command = zsh_to_fish(command)
if is_valid_fish(command):
time = meta.split(':')[1].strip()
print('Add', command)
o.write('- cmd: %s\n when: %s\n' % (command, time))
@espinuevajaime
Copy link

Thanks still works!

@tekacs
Copy link

tekacs commented Jun 29, 2019

Still works, thanks! :)

@pholat
Copy link

pholat commented Apr 22, 2020

👍

@depau
Copy link

depau commented Jun 22, 2020

I had some encoding issues while running it with my history. I fixed it like this:

--- zsh_to_fish.py	2020-06-22 02:13:36.311314807 +0200
+++ zsh_to_fish_fixed.py	2020-06-22 02:12:12.530619810 +0200
@@ -15,8 +15,9 @@
 
 
 with open(os.path.expanduser('~/.local/share/fish/fish_history'), 'a') as o:
-    with open(os.path.expanduser('~/.zsh_history')) as f:
+    with open(os.path.expanduser('~/.zsh_history'), 'rb') as f:
         for line in f:
+            line = line.decode(errors='replace')
             line = line.strip()
             if line and re.match('^:\s+\d+:\d;', line):
                 meta, command = line.split(';', 1)
@@ -25,3 +26,4 @@
                     time = meta.split(':')[1].strip()
                     print('Add', command)
                     o.write('- cmd: %s\n   when: %s\n' % (command, time))
+

@grzkv
Copy link

grzkv commented Jul 8, 2020

@depau Had the same. Fix works. Thanks.

@jose1711
Copy link

👍

@amordo
Copy link

amordo commented Dec 5, 2022

@depau +1, ty!

@VasiliyMooduckovich
Copy link

not so great
Traceback (most recent call last): File "zsh_to_fish.py", line 19, in <module> for line in f: File "/usr/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 2329: invalid start byte

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment