#!/bin/sh # The MIT License (MIT) # # Copyright (c) 2026 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # pbn [options...] [line numbers...] # # Pick (lines) By Number, using all the 1-based line-numbers given, or even # negative ones, which count backward from the last line. Input lines always # come from the standard input. # # The options are, available both in single and double-dash versions # # -h, -help show this help message buffered=0 case "$1" in -b|--b|-buffered|--buffered) buffered=1; shift ;; -h|--h|-help|--help) awk '/^# +pbn /, /^$/ { gsub(/^# ?/, ""); print }' "$0" exit 0 ;; --) shift ;; -*) if echo "$1" | grep -E -q '^-[^0-9]+$'; then printf "unsupported option '%s'\n" "$1" >&2 exit 1 fi ;; esac if [ $# -eq 0 ]; then awk '/^# +pbn /, /^$/ { gsub(/^# ?/, ""); print }' "$0" exit 1 fi flush=0 if [ "${buffered}" -eq 0 ] && { [ -p /dev/stdout ] || [ -t 1 ]; }; then flush=1 fi awk -v flush="${flush}" ' BEGIN { for (i = 1; i < ARGC; i++) { p = ARGV[i] delete ARGV[i] if (p != 0) picks[++npicks] = p } j = 1 out = 0 if (npicks == 0) exit 1 min = max = picks[1] for (i = 1; i <= npicks; i++) { p = picks[i] if (min > p) min = p if (max < p) max = p } } { # try to emit leading picks right away, in case of live-lines output while ((j <= npicks) && (picks[j] == NR)) { print if (flush) fflush() out++ picks[j] = 0 j++ } # no need to read more input if all picks have already been output if (j > npicks) exit # no need to remember lines before the first pick: `NR` is always # at least 1, so the condition is always false with a negative `min` if (NR < min) next # no need to remember lines past the last index, when no index is # negative/backwards if ((min >= 0) && (NR > max)) exit lines[NR] = $0 } END { if (npicks == 0) exit 1 # output any picks not yet emitted for (i = j; i <= npicks; i++) { p = picks[i] if (p < 0) p += NR + 1 if (1 <= p && p <= NR) { print lines[p]; out++ } } exit(out == 0) } ' "$@"