Skip to content

Instantly share code, notes, and snippets.

@JeanDavidDaviet
Created August 13, 2025 12:05
Show Gist options
  • Select an option

  • Save JeanDavidDaviet/f91dea04731e84d848716338314ce875 to your computer and use it in GitHub Desktop.

Select an option

Save JeanDavidDaviet/f91dea04731e84d848716338314ce875 to your computer and use it in GitHub Desktop.
I've kept my old history from when using bash and I wanted to switch it to the .zsh_history format. (Mainly changing the date actually)
#!/usr/bin/env python3
"""
Script to convert old bash history format to zsh history format.
Old format: "1 17.11.2023 14:57 command_executed"
New format: ": 1753098256:0;command_executed"
"""
import re
import sys
from datetime import datetime
import shutil
def convert_date_to_timestamp(date_str, time_str):
"""Convert date and time strings to Unix timestamp."""
try:
# Parse the date and time
dt_str = f"{date_str} {time_str}"
dt = datetime.strptime(dt_str, "%d.%m.%Y %H:%M")
# Convert to Unix timestamp
return int(dt.timestamp())
except ValueError:
# If parsing fails, use a default timestamp
return 1753098256
def convert_history_line(line):
"""Convert a single history line from old format to new format."""
# Pattern to match: number, date, time, command
# Support both DD.MM.YYYY and D.M.YYYY formats
pattern = r'^\s*\d+\s+(\d{1,2}\.\d{1,2}\.\d{4})\s+(\d{1,2}:\d{2})\s+(.+)$'
match = re.match(pattern, line.strip())
if not match:
# If line doesn't match expected format, skip it
return None
date_str, time_str, command = match.groups()
timestamp = convert_date_to_timestamp(date_str, time_str)
# Format: ": timestamp:0;command"
return f": {timestamp}:0;{command}"
def main():
input_file = "history.txt"
output_file = "history_converted.txt"
try:
# Create a backup copy first
shutil.copy(input_file, f"{input_file}.backup")
print(f"Created backup: {input_file}.backup")
converted_lines = []
with open(input_file, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
converted = convert_history_line(line)
if converted:
converted_lines.append(converted)
else:
print(f"Warning: Could not parse line {line_num}: {line.strip()}")
# Write converted lines to output file
with open(output_file, 'w', encoding='utf-8') as f:
for line in converted_lines:
f.write(line + '\n')
print(f"Conversion complete!")
print(f"Input file: {input_file}")
print(f"Output file: {output_file}")
print(f"Converted {len(converted_lines)} history entries")
print(f"\nTo prepend to your .zsh_history, run:")
print(f"cat {output_file} ~/.zsh_history > ~/.zsh_history.new && mv ~/.zsh_history.new ~/.zsh_history")
except FileNotFoundError:
print(f"Error: {input_file} not found!")
sys.exit(1)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment