-
Notifications
You must be signed in to change notification settings - Fork 1
/
cut.py
174 lines (144 loc) · 5.46 KB
/
cut.py
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python3
'''
Name: Hamdy Abou El Anein
Email: hamdy.aea@protonmail.com
Date of creation: 22-11-2024
Last update: 22-11-2024
Version: 1.0
Description: The cut command from GNU coreutils in Python3.
Example of use: python cut.py -c 1-3 file.txt
'''
import sys
import argparse
class CutCommand:
def __init__(self, mode, fields, delimiter='\t', suppress_non_delimited=False):
"""
Initialize Cut command with specified parameters.
Args:
mode (str): 'bytes', 'chars', or 'fields'
fields (list): List of field/character ranges to extract
delimiter (str): Field delimiter
suppress_non_delimited (bool): Suppress lines without delimiter
"""
self.mode = mode
self.fields = self._parse_ranges(fields)
self.delimiter = delimiter
self.suppress_non_delimited = suppress_non_delimited
def _parse_ranges(self, ranges):
"""
Parse field/character ranges.
Args:
ranges (list): List of range strings
Returns:
list: Parsed and validated ranges
"""
parsed_ranges = []
for range_str in ranges:
try:
if '-' in range_str:
start, end = map(int, range_str.split('-'))
parsed_ranges.append((start, end))
else:
parsed_ranges.append((int(range_str), int(range_str)))
except ValueError:
raise ValueError(f"Invalid range: {range_str}")
return parsed_ranges
def process_line(self, line):
"""
Process a single line based on mode and ranges.
Args:
line (str): Input line to process
Returns:
str: Processed line or None
"""
# Decode if bytes, strip newline
if isinstance(line, bytes):
line = line.decode('utf-8').rstrip('\n')
if self.mode == 'fields':
return self._process_fields(line)
elif self.mode in ['bytes', 'chars']:
return self._process_chars(line)
return line
def _process_fields(self, line):
"""
Process line by extracting specified fields.
Args:
line (str): Input line
Returns:
str: Processed line or None
"""
# Check delimiter
parts = line.split(self.delimiter)
# Suppress non-delimited lines if required
if self.suppress_non_delimited and len(parts) < 2:
return None
# Extract fields
selected_fields = []
for start, end in self.fields:
# Adjust for 0-based indexing
start -= 1
end = min(end, len(parts))
selected_fields.extend(parts[start:end])
return self.delimiter.join(selected_fields)
def _process_chars(self, line):
"""
Process line by extracting specified characters.
Args:
line (str): Input line
Returns:
str: Processed line
"""
result = []
for start, end in self.fields:
# Adjust for 0-based indexing
start -= 1
# Extract characters
result.append(line[start:end])
return ''.join(result)
def main():
"""
Main function to handle cut command functionality.
"""
parser = argparse.ArgumentParser(description='Cut out selected portions of each line of files')
# Mutually exclusive selection modes
selection_group = parser.add_mutually_exclusive_group(required=True)
selection_group.add_argument('-b', '--bytes',
help='Select only these bytes')
selection_group.add_argument('-c', '--characters',
help='Select only these characters')
selection_group.add_argument('-f', '--fields',
help='Select only these fields')
# Additional options
parser.add_argument('-d', '--delimiter',
default='\t',
help='Use DELIM instead of TAB for field delimiter')
parser.add_argument('-s', '--only-delimited',
action='store_true',
help='Suppress lines with no delimiter')
parser.add_argument('files', nargs='*',
type=argparse.FileType('rb'),
default=[sys.stdin.buffer],
help='Input files (default: stdin)')
args = parser.parse_args()
# Determine mode and create CutCommand instance
if args.bytes:
cut_command = CutCommand('bytes', args.bytes.split(','))
elif args.characters:
cut_command = CutCommand('chars', args.characters.split(','))
elif args.fields:
cut_command = CutCommand('fields',
args.fields.split(','),
delimiter=args.delimiter,
suppress_non_delimited=args.only_delimited)
# Process input files
try:
for file in args.files:
for line in file:
processed_line = cut_command.process_line(line)
if processed_line is not None:
print(processed_line)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()