-
Notifications
You must be signed in to change notification settings - Fork 0
/
getsection
executable file
·43 lines (38 loc) · 1.76 KB
/
getsection
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
#!/usr/bin/env python3
"""
Extract one or more sections from an ORG file
"""
import argparse
import sys
if __name__=="__main__":
# Parse args
parser = argparse.ArgumentParser(description="Extract one or more sections from an org file, and save or print to stdout")
parser.add_argument("-i", "--infile", type=str, default=None, help="Org file from which to extract sections, default stdin")
parser.add_argument("sections", nargs="+", help="One or more sections to extract, in desired order")
parser.add_argument("-o", "--output", type=str, default=None, help="Output file, default stdout")
args = parser.parse_args()
output_lines = []
# Search for each section, one by one
for section in args.sections:
# Open the file afresh for each search
with (open(args.infile, 'r') if args.infile else sys.stdin) as infile:
in_target_section = False
for line in infile:
# Check if we're at a new section
split_line = line.split()
if len(split_line)>1 and split_line[0]=='*':
# Have reached a new section
if in_target_section:
# If we were in the target section previously, we no longer are
# Record this section, then break to start looking for next patterns to match
output_lines.append('\n')
break
if split_line[1] == section:
in_target_section = True
if in_target_section:
output_lines.append(line)
if args.output is None:
print(''.join(output_lines))
else:
with open(args.output, 'w') as outfile:
outfile.write(''.join(output_lines))