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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
|
use std::error::Error;
use std::io;
use std::process;
use csv;
use docopt;
use regex;
use serde_derive::Deserialize;
#[derive(Debug)]
enum MyError {
ColumnNotFound,
Csv(csv::Error),
Io(io::Error),
Regex(regex::Error),
ParseInt(std::num::ParseIntError),
}
impl Error for MyError {}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
MyError::ColumnNotFound => write!(f, "column not found"),
MyError::Csv(e) => e.fmt(f),
MyError::Io(e) => e.fmt(f),
MyError::Regex(e) => e.fmt(f),
MyError::ParseInt(e) => e.fmt(f),
}
}
}
impl From<csv::Error> for MyError {
fn from(error: csv::Error) -> Self {
if error.is_io_error() {
let error = error.into_kind();
match error {
csv::ErrorKind::Io(e) => MyError::Io(e),
_ => unreachable!(),
}
} else {
MyError::Csv(error)
}
}
}
impl From<io::Error> for MyError {
fn from(error: io::Error) -> Self {
MyError::Io(error)
}
}
impl From<regex::Error> for MyError {
fn from(error: regex::Error) -> Self {
MyError::Regex(error)
}
}
impl From<std::num::ParseIntError> for MyError {
fn from(error: std::num::ParseIntError) -> Self {
MyError::ParseInt(error)
}
}
const USAGE: &'static str = "
csvre
A simple tool for replacing data in CSV columns with regular
expressions.
USAGE:
csvre [options] --column=COLUMN <regex> <replacement>
csvre (-h | --help)
csvre --version
ARGUMENTS:
<regex>
Regular expression used for matching.
For syntax documentation, see
https://docs.rs/regex/1.1.2/regex/#syntax
Some information about unicode handling can be found from
https://docs.rs/regex/1.1.2/regex/#unicode
<replacement>
Replacement string.
You can reference named capture groups in the regex with $name and
${name} syntax. You can also use integers to reference capture
groups with $0 being the whole match, $1 the first group and so on.
If a capture group is not valid (name does not exist or index is
invalid), it is replaced with the empty string.
To insert a literal $, use $$.
OPTIONS:
-h, --help
Show this message.
--version
Show the version number.
-d DELIM, --delimiter=DELIM
Field delimiter. This is used for both input and output.
[default: ,]
-c COLUMN, --column=COLUMN
Which column to operate on.
You can either use the column name or zero based index. If
you specify --no-headers, then you can only use the index
here.
-n, --no-headers
The input does not have a header row.
If you use this option, you can do matching against the first
row of input.
-b, --bytes
Don't assume utf-8 input, work on raw bytes instead.
See https://docs.rs/regex/1.1.2/regex/bytes/index.html#syntax
for differences to the normal matching rules.
";
#[derive(Deserialize)]
struct Args {
arg_regex: String,
arg_replacement: String,
flag_delimiter: String,
flag_column: String,
flag_no_headers: bool,
flag_bytes: bool,
}
fn main() {
match run() {
Ok(()) => (),
Err(error) => {
match error {
MyError::Io(ref error) => {
if error.kind() == io::ErrorKind::BrokenPipe {
return;
}
}
_ => (),
}
eprintln!("error: {}", error);
process::exit(1);
}
}
}
fn run() -> Result<(), MyError> {
let version = format!(
"{}.{}.{}",
env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MINOR"),
env!("CARGO_PKG_VERSION_PATCH")
);
let args: Args = docopt::Docopt::new(USAGE)
.and_then(|d| d.help(true).version(Some(version)).deserialize())
.unwrap_or_else(|e| e.exit());
let delimiter = args.flag_delimiter.as_bytes()[0];
let column_str = args.flag_column;
// (Ab)use Result as kind of an Either type ... :-)
let re = if args.flag_bytes {
Err(regex::bytes::Regex::new(&args.arg_regex)?)
} else {
Ok(regex::Regex::new(&args.arg_regex)?)
};
let replacement = if args.flag_bytes {
Err(args.arg_replacement.as_bytes())
} else {
Ok(args.arg_replacement.as_str())
};
let mut reader = csv::ReaderBuilder::new()
.delimiter(delimiter)
.has_headers(!args.flag_no_headers)
.flexible(true)
.from_reader(io::stdin());
let mut writer = csv::WriterBuilder::new()
.delimiter(delimiter)
.flexible(true)
.from_writer(io::stdout());
// If we have headers, and we cannot parse column as an integer,
// then we try to check if the column is included in the headers.
let column_index: usize = if reader.has_headers() {
reader.byte_headers()?;
match column_str.parse() {
Ok(n) => n,
Err(_) => {
if args.flag_bytes {
reader
.byte_headers()?
.iter()
.position(|x| x == column_str.as_bytes())
.ok_or(MyError::ColumnNotFound)?
} else {
reader
.headers()?
.iter()
.position(|x| x == column_str)
.ok_or(MyError::ColumnNotFound)?
}
}
}
} else {
column_str.parse()?
};
if args.flag_bytes {
run_bytes(
&mut reader,
&mut writer,
column_index,
re.as_ref().unwrap_err(),
replacement.unwrap_err(),
)?;
} else {
run_string(
&mut reader,
&mut writer,
column_index,
re.as_ref().unwrap(),
replacement.unwrap(),
)?;
}
writer.flush()?;
Ok(())
}
fn run_string<R, W>(
reader: &mut csv::Reader<R>,
writer: &mut csv::Writer<W>,
column_index: usize,
re: ®ex::Regex,
replacement: &str,
) -> Result<(), MyError>
where
R: io::Read,
W: io::Write,
{
let mut record_in = csv::StringRecord::new();
let mut record_out = csv::StringRecord::new();
if reader.has_headers() {
writer.write_record(reader.headers()?)?;
}
while reader.read_record(&mut record_in)? {
record_out.clear();
for index in 0..record_in.len() {
let field = record_in.get(index).unwrap();
let result = if index == column_index {
re.replace_all(field, replacement)
} else {
std::borrow::Cow::Borrowed(field)
};
record_out.push_field(&result);
}
writer.write_record(&record_out)?;
}
Ok(())
}
fn run_bytes<R, W>(
reader: &mut csv::Reader<R>,
writer: &mut csv::Writer<W>,
column_index: usize,
re: ®ex::bytes::Regex,
replacement: &[u8],
) -> Result<(), MyError>
where
R: io::Read,
W: io::Write,
{
let mut record_in = csv::ByteRecord::new();
let mut record_out = csv::ByteRecord::new();
if reader.has_headers() {
writer.write_byte_record(reader.byte_headers()?)?;
}
while reader.read_byte_record(&mut record_in)? {
record_out.clear();
for index in 0..record_in.len() {
let field = record_in.get(index).unwrap();
let result = if index == column_index {
re.replace_all(field, replacement)
} else {
std::borrow::Cow::Borrowed(field)
};
record_out.push_field(&result);
}
writer.write_byte_record(&record_out)?;
}
Ok(())
}
|