Last active
November 20, 2025 14:37
-
-
Save jpic/715f46ba7c32228db9f0d97ce90dca68 to your computer and use it in GitHub Desktop.
file read tool
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
| read_file_slice() { | |
| local path="$1" | |
| local start_byte="${2:-0}" | |
| local length="${3:-32768}" | |
| local show_hex="${4:-false}" | |
| # Safety caps | |
| (( length > 131072 )) && length=131072 | |
| (( start_byte < 0 )) && start_byte=0 | |
| # Resolve path | |
| path=$(realpath "$path" 2>/dev/null || printf '%s\n' "$path") | |
| # Header | |
| printf '[read_file_slice] %s\n' "$path" | |
| printf '[Requested bytes: %d–%d (%d bytes)]\n\n' \ | |
| "$start_byte" "$((start_byte + length - 1))" "$length" | |
| # ── Extract the exact byte range ───────────────────────────────────── | |
| if [[ "$path" == *.gz ]]; then | |
| block_size=1048576 | |
| approx_block=$(( start_byte / block_size )) | |
| offset_in_block=$(( start_byte % block_size )) | |
| (dd if="$path" bs="$block_size" skip="$approx_block" count=8 status=none 2>/dev/null || true) | | |
| gzip -dc 2>/dev/null | | |
| dd bs=1 skip="$offset_in_block" count="$length" status=none 2>/dev/null | |
| else | |
| dd if="$path" bs=1 skip="$start_byte" count="$length" status=none 2>/dev/null | |
| fi | { | |
| # Read everything once (preserves NUL bytes!) | |
| IFS= read -r -d '' data || true | |
| if [ "$show_hex" = true ]; then | |
| printf '[show_hex forced → hexdump]\n' | |
| printf '%s' "$data" | hexdump -ve '1/1 "%.02X "' -e '16/1 "%_c" "\n"' | |
| return | |
| fi | |
| # Detect binary: >15% non-printable/control chars in first 32KB | |
| nonprint=$(printf '%s' "$data" | head -c 32768 | | |
| tr -d -c '[\001-\010\016-\037\177-\377]' | wc -c) | |
| if (( nonprint * 100 <= 32768 * 15 )); then | |
| # Text → raw output | |
| printf '%s' "$data" | |
| else | |
| # Binary → hexdump | |
| printf '[BINARY DETECTED → hexdump of requested range]\n' | |
| printf '%s' "$data" | hexdump -ve '1/1 "%.02X "' -e '16/1 "%_c" "\n"' | |
| fi | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.