#!/usr/bin/env bash # len2nl.sh — convert length-prefixed and/or MLLP-framed HL7 to newline-readable. # # Handles both common framing patterns: # 1. Length-prefix: `MSH|...` → strip leading digits before MSH # 2. MLLP: `\x0b...\x1c\x0d` → strip VT and FS+CR end-block # 3. Segment CRs: `\r\r...` → replace \r with \n # # After conversion, each segment is on its own line (LF), making the message # greppable / pageable. # # Usage: # len2nl.sh [FILE] # file or stdin # cat raw.hl7 | len2nl.sh # tcpdump ... | len2nl.sh # # This is a strict superset of the v1 `len2nl` behavior. set -o pipefail usage() { sed -n '2,18p' "$0"; exit 0; } case "${1:-}" in -h|--help) usage ;; esac INPUT="${1:-}" if [ -n "$INPUT" ] && [ ! -f "$INPUT" ]; then echo "len2nl: no such file: $INPUT" >&2; exit 2 fi if [ -n "$INPUT" ]; then CMD=(cat "$INPUT") else CMD=(cat) fi "${CMD[@]}" \ | tr -d '\013' `# strip MLLP VT (0x0B = start-block)` \ | sed 's/\x1c\x0d//g' `# strip MLLP FS+CR (0x1C 0x0D = end-block)` \ | sed -E 's/[0-9]+MSH\|/MSH|/g' `# strip numeric length-prefix before MSH` \ | tr '\r' '\n' `# CR-separated segments → LF`