-
cleemy desu wayo authored923c08df
yass-c-sed.py 1.86 KiB
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
59
60
61
62
63
#!/usr/bin/env python3
#
# ==========================================================================
# yass-c-sed.py -- version 0.0.99.20231019
#
# written by cleemy desu wayo / Licensed under CC0 1.0
#
# official repository: https://gitlab.com/cleemy-desu-wayo/yass
# ==========================================================================
import sys
import re
def error_exit(error_msg):
print(f'ERROR: {error_msg}', file=sys.stderr)
sys.exit(1)
if len(sys.argv) <= 1:
error_exit('lack of sed code')
m = re.match(r'(/[0-9a-zA-Z]+/);(.*)', sys.argv[1])
if m is None:
error_exit('specify a delimiter at the beginning (such as "/a62z4E2hH2q/;")')
delimiter = m.group(1)
sed_code_body = m.group(2)
sed_code_list = []
tmp_list = sed_code_body.split(delimiter)
for i, token in enumerate(tmp_list):
if i == 0:
if token.lstrip() != 's':
error_exit('invalid sed code (1)')
token_list = ['s']
elif i % 3 == 0:
if token.startswith('g'):
token_list.append('g')
else:
token_list.append('')
token = re.sub(r'g?\s*', '', token, 1)
if i == (len(tmp_list) - 1):
m = re.match(r';?\s*$', token)
if m is None:
error_exit('invalid sed code (2)')
else:
m = re.match(r';\s*s$', token)
if m is None:
error_exit('invalid sed code (3)')
sed_code_list.append(token_list)
token_list = ['s']
elif i % 3 == 1 or i % 3 == 2:
token_list.append(token)
for line in [s.rstrip('\r\n') for s in sys.stdin]:
replaced_line = line
for token_list in sed_code_list:
if token_list[3] == 'g':
replaced_line = replaced_line.replace(token_list[1], token_list[2])
else:
replaced_line = replaced_line.replace(token_list[1], token_list[2], 1)
print(replaced_line)