-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtop-level-section
executable file
·58 lines (56 loc) · 1.45 KB
/
top-level-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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#! /bin/sh
# top-level-section - print top level section containing line matching regexp
#
# Copyright (C) 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: top-level-section PATTERN [FILE...]'; exit 1; }
PATTERN="$(printf -- '%s' "$1" | sed 's/\\/&&/g')"
shift
exec /usr/bin/awk -v pattern="$PATTERN" -- '
BEGIN {
top_ind_len = -1
next_line_no = 1
}
function print_saved_lines() {
for (i = 1; i < next_line_no; i++) {
print saved_lines[i]
}
next_line_no = 1
}
function save_current_line() {
saved_lines[next_line_no] = $0
next_line_no++
}
function delete_saved_lines() {
next_line_no = 1
}
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 (top_ind_len == -1) {
top_ind_len = loc_ind_len
} else if (loc_ind_len <= top_ind_len) {
top_ind_len = loc_ind_len
delete_saved_lines()
}
if (pat_match || (in_section && loc_ind_len > top_ind_len)) {
if (pat_match && !in_section) {
print_saved_lines()
}
in_section = 1
print $0
} else {
save_current_line()
in_section = 0
}
}
$0 ~ pattern { update_state(1) }
$0 !~ pattern { update_state(0) }
' "$@"