Skip to content

Instantly share code, notes, and snippets.

@jedypod
Last active August 23, 2016 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jedypod/63c13661fff4d0378448 to your computer and use it in GitHub Desktop.
Save jedypod/63c13661fff4d0378448 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from __future__ import with_statement
import os, re, argparse
# Convert one machine code format to another -
# rename this with no py extension, make it executable, and put it in your bash PATH to make it a commandline tool
# This uses the argparse module to parse args to the commandline tool
parser = argparse.ArgumentParser()
parser.add_argument("src_file", help="The source text file of machine code to convert.")
parser.add_argument('-d', '--destination', help="Specify the destination file. Uses <origname>_conv.txt otherwise.")
# Grab the arguments to use (could add more for different conversion formats or whatever)
args = parser.parse_args()
destination = args.destination
src_file = args.src_file
if destination:
destination_name = destination
else:
destination_name = os.path.splitext(src_file)[0]+'_conv.txt'
# Open the original file for reading, and the new file for writing
with open(src_file, 'r+') as src_f:
with open(destination_name, 'w+') as dst_f:
# Loop through each line of the file
for line in src_f:
# Compile a regular expression that matches Y## or X##
query = re.compile('([X,Y][0-9]{2})')
# Use re.sub to take the match and add a '.' character to the end
line_converted = re.sub(query, r'\1.', line)
# You could also use match group 0 instead of \1 like this but it's more verbose
# lambda creates a function in-line
# line_converted = re.sub(query, lambda match: match.group(0)+'.', line)
# Write our converted line to the new file
dst_f.write(line_converted)
# Or you could use bash with sed if you put this in your ~/.bash_profile
# function convert { (sed -E 's/([X,Y][0-9]{2})/\1./g' $1 > ${1}_conv;) }
# -E uses extended modern regular expressions so you don't have to escape the group definitions
# \1 refers to the first group (same as $1 in sublime/perl/java)
# Example to open each line of a text file and do stuff to it.
from __future__ import with_statement
bg_db_path = '/Volumes/af/show/wash/common/nuke/RF_SEQ_BG_DB'
bg_db = {}
with open(bg_db_path) as f:
for line in f:
line = line.strip()
# Skip commented and blank lines
if line.startswith('#') or not line:
continue
line_info = line.split('\t')
bg_db[line_info[0]] = line_info[1:3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment