-
Notifications
You must be signed in to change notification settings - Fork 0
/
section
executable file
·35 lines (33 loc) · 1.01 KB
/
section
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
#! /bin/sh
# section - print line matching regexp with following indented section
#
# Copyright (C) 2018-2021 by Erik Auerswald <[email protected]>
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved. This file is offered as-is,
# without any warranty.
test -z "$1" && { echo 'Usage: section PATTERN [FILE...]'; exit 1; }
PATTERN="$(printf -- '%s' "$1" | sed 's/\\/&&/g')"
shift
exec /usr/bin/awk -v pattern="$PATTERN" -- '
function update_state(pat_match, loc_ind) {
if (match($0, /^[ \t]+/)) {
loc_ind = substr($0, RSTART, RLENGTH)
gsub(/\t/, " ", loc_ind)
}
loc_ind_len = length(loc_ind)
if (pat_match || (in_section && (loc_ind_len > ind_len))) {
if (!in_section || (loc_ind_len <= ind_len)) {
ind_len = loc_ind_len
}
in_section = 1
print $0
} else {
in_section = 0
ind_len = 0
}
}
$0 ~ pattern { update_state(1) }
$0 !~ pattern { update_state(0) }
' "$@"