Created
August 29, 2026 17:09
-
-
Save grejc/21aa8eb3ed9d8e79b0812631a5e0081a to your computer and use it in GitHub Desktop.
View CSV from terminal
This file contains hidden or 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
| # ---- CSV Visualizer ---- | |
| viewcsv() { | |
| if [ -z "$1" ]; then | |
| echo "Uso: viewcsv <arquivo.csv> [num_linhas]" >&2 | |
| return 1 | |
| fi | |
| python3 -c ' | |
| import sys, csv, unicodedata | |
| def char_width(s): | |
| """Calcula a largura real de exibição no terminal.""" | |
| return sum(2 if unicodedata.east_asian_width(c) in ("F", "W") else 1 for c in s) | |
| def pad_str(s, width): | |
| """Aplica ljust baseando-se na largura visual dos caracteres.""" | |
| w = char_width(s) | |
| return s + " " * max(0, width - w) | |
| filepath = sys.argv[1] | |
| limit = int(sys.argv[2]) if len(sys.argv) > 2 else 10 | |
| try: | |
| with open(filepath, mode="r", newline="", encoding="utf-8-sig") as f: | |
| reader = csv.reader(f) | |
| try: | |
| header = next(reader) | |
| except StopIteration: | |
| print("Erro: O arquivo está vazio.", file=sys.stderr) | |
| sys.exit(1) | |
| rows = [] | |
| for _ in range(limit): | |
| try: | |
| rows.append(next(reader)) | |
| except StopIteration: | |
| break | |
| if not rows: | |
| print("Arquivo contém apenas o cabeçalho.") | |
| sys.exit(0) | |
| # Garante que todas as linhas tenham a mesma quantidade de colunas do cabeçalho | |
| num_cols = len(header) | |
| normalized_rows = [r + [""] * (num_cols - len(r)) for r in rows] | |
| # Transposição: cada item é (Nome da Coluna, [Valores das linhas...]) | |
| transposed = [(h, [r[i] for r in normalized_rows]) for i, h in enumerate(header)] | |
| # Largura da coluna de nomes (coluna 0) | |
| col0_w = max(char_width(h) for h, _ in transposed) | |
| # Largura individual para cada sub-coluna de dados (L1, L2, ...) | |
| num_samples = len(normalized_rows) | |
| val_widths = [ | |
| max(char_width(t[1][row_idx]) for t in transposed) | |
| for row_idx in range(num_samples) | |
| ] | |
| # Formatação e desenho da tabela | |
| sep_top = "═" * (col0_w + 2) + "╦" + "╦".join("═" * (w + 2) for w in val_widths) | |
| sep_bot = "═" * (col0_w + 2) + "╩" + "╩".join("═" * (w + 2) for w in val_widths) | |
| print(f"╔{sep_top}╗") | |
| for col_name, vals in transposed: | |
| col0_formatted = pad_str(col_name, col0_w) | |
| vals_formatted = " ║ ".join(pad_str(vals[i], val_widths[i]) for i in range(len(vals))) | |
| print(f"║ {col0_formatted} ║ {vals_formatted} ║") | |
| print(f"╚{sep_bot}╝") | |
| except FileNotFoundError: | |
| print(f"Erro: Arquivo \"{filepath}\" não encontrado.", file=sys.stderr) | |
| sys.exit(1) | |
| ' "$1" "${2:-10}" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment