-
-
Save ktilcu/ad317a1c12cb26f25ec27074b21afd4c to your computer and use it in GitHub Desktop.
Aligning `paste` alternative
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse | |
import itertools | |
ap = argparse.ArgumentParser() | |
ap.add_argument('file', nargs='*', type=argparse.FileType('r')) | |
ap.add_argument('-p', '--pad-char', default=' ') | |
ap.add_argument('-d', '--delimiter', default=' ') | |
ap.add_argument('-c', '--pad-color', default=None) | |
ap.add_argument('-s', '--align-spec', default='') | |
args = ap.parse_args() | |
columns = [[line.rstrip('\n\r') for line in f] for f in args.file] | |
max_widths = [max(map(len, col), default=0) for col in columns] | |
max_width_items = [max(col, key=len) for col in columns] | |
pad_color_str = f'\033[{args.pad_color}m' if args.pad_color else '' | |
pad_color_reset_str = f'\033[0m' if args.pad_color else '' | |
spec = args.align_spec | |
def align_to_spec(text, width, pad, i): | |
if i >= len(spec) or spec[i] == 'l': | |
return (text + pad_color_str).ljust(width + len(pad_color_str), pad) + pad_color_reset_str | |
elif spec[i] == 'r': | |
return pad_color_str + (pad_color_reset_str + text).rjust(width + len(pad_color_reset_str), pad) | |
raise ValueError(f'invalid spec {spec[i]}') | |
for row in itertools.zip_longest(*columns, fillvalue=''): | |
formatted_row = [] | |
for i, cell in enumerate(row): | |
formatted_row.append(align_to_spec(cell, max_widths[i], args.pad_char, i)) | |
print(args.delimiter.join(formatted_row)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment