-
Notifications
You must be signed in to change notification settings - Fork 34
/
catn
executable file
·43 lines (35 loc) · 946 Bytes
/
catn
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/bin/bash
usage() {
local bin=${0##*/}
[[ $1 -eq 0 ]] || exec 1>&2
echo "Usage: $bin [-q] file line ctx_lines"
echo " or: $bin [-q] file line[:ctx_lines]"
echo " or: $bin [-q] file:line[:ctx_lines]"
# [[ $1 -ne 0 ]] || { echo; echo "more help stuff"; }
exit ${1:-1}; }
[[ "$1" != -h && "$1" != --help ]] || usage 0
q=
[[ "$1" = -q ]] && { q=t; shift; }
[[ -n "$1" ]] || usage 1
# set -eo pipefail
ctx=
case "$#" in
3) file=$1 line=$2 ctx=$3 ;;
2) file=$1 line=$2 ;;
1)
[[ $1 =~ : ]] || usage 1
file=${1%:*} line=${1#*:} ;;
0) usage ;;
*) usage 1
esac
[[ -z "$file" || -z "$line" ]] && usage 1
[[ -z "$ctx" ]] && {
[[ $line =~ : ]] && ctx=${line#*:} || ctx=3
}
line=${line%:*}
line_min=$(( $line - $ctx ))
line_max=$(( $line + $ctx ))
[[ -z "$q" ]]\
&& line_fmt='{pre=NR=='"$line"' ? ">>" : " "; printf("%s %d: %s\n", pre, NR, $0)}'\
|| line_fmt=''
exec awk "NR>=${line_min} && NR<=${line_max} ${line_fmt}" "$file"