2 * A Swiss-Army Knife for CSV-like Files
4 * (c) 2012 Martin Mares <mj@ucw.cz>
15 /*** Memory allocation ***/
17 static void *xmalloc(size_t bytes)
19 void *p = malloc(bytes);
21 fprintf(stderr, "xsv: Out of memory (cannot allocate %zu bytes)\n", bytes);
27 static void *xrealloc(void *old, size_t bytes)
29 void *p = realloc(old, bytes);
31 fprintf(stderr, "xsv: Out of memory (cannot allocate %zu bytes)\n", bytes);
37 #define DECLARE_BUF(name, type) \
38 typedef struct { type *start; int count; int max; } name##_t; \
39 static inline void name##_init(name##_t *b) { b->start = NULL; b->count = b->max = 0; } \
40 static inline void name##_reset(name##_t *b) { b->count = 0; } \
41 static inline int name##_count(name##_t *b) { return b->count; } \
42 static void name##_extend(name##_t *b) { \
43 b->max = b->max ? 2*b->max : 16; \
44 b->start = xrealloc(b->start, b->max * sizeof(type)); \
46 static inline type *name##_push(name##_t *b) { \
47 if (b->count >= b->max) name##_extend(b); \
48 return &b->start[b->count++]; \
50 static inline type *name##_first(name##_t *b) { return b->start; } \
51 static inline type *name##_nth(name##_t *b, int n) { return &b->start[n]; } \
54 /*** Formats and their parameters ***/
69 int (*read_line)(void);
70 void (*write_line)(void);
75 pcre_extra *pcre_extra;
78 static struct format *in_format, *out_format;
85 DECLARE_BUF(fields, struct field);
86 DECLARE_BUF(line, unsigned char);
88 static fields_t in_fields, out_fields;
89 static struct field *in_field;
90 static line_t in_line;
91 static int line_number;
93 static void new_field(int pos)
95 in_field = fields_push(&in_fields);
96 in_field->start_pos = pos;
100 static void ensure_field(int pos)
106 static void warn(struct format *fmt, char *msg, ...)
109 fprintf(stderr, "Warning at line %d: ", line_number);
112 vfprintf(stderr, args, msg);
118 static int next_line(void)
125 return !!line_count(&in_line);
128 *line_push(&in_line) = c;
132 static int csv_read(void)
137 int i = line_count(&in_line);
141 if (c < 0 || c == '\n') {
143 warn(in_format, "Missing closing quote.");
145 return !!fields_count(&in_fields);
150 if (c == in_format->quote) {
152 if (c != in_format->quote) {
156 // Two quotes assimilate to one
158 // Fall through to pushing the character
159 } else if (c == in_format->quote) {
162 } else if (c == in_format->fs && !quoted) {
168 *line_push(&in_line) = c;
173 static int is_ws(int c)
175 return (c == ' ' || c == '\t' || c == '\f');
178 static void csv_write(void)
180 unsigned char *line = line_first(&in_line);
181 int n = fields_count(&out_fields);
182 for (int i=0; i<n; i++) {
183 struct field *f = fields_nth(&out_fields, i);
185 if (out_format->quote >= 0) {
186 need_quotes = out_format->always_quote;
187 for (int j=0; !need_quotes && j < f->len; j++) {
188 int c = line[f->start_pos + j];
189 if (c == out_format->fs || c == out_format->quote)
194 putchar(out_format->fs);
196 putchar(out_format->quote);
197 for (int j=0; j < f->len; j++) {
198 int c = line[f->start_pos + j];
199 if (c == out_format->fs && !need_quotes)
200 warn(out_format, "Field separator found inside field and quoting is turned off.");
201 if (c == out_format->quote)
206 putchar(out_format->quote);
211 static int ws_read(void)
216 unsigned char *line = line_first(&in_line);
217 int n = line_count(&in_line);
223 for (int i=0; i<n; i++) {
241 static const char *regex_set(struct format *f, char *rx)
245 f->pcre = pcre_compile(rx, PCRE_DOLLAR_ENDONLY, &err, &errpos, NULL);
249 f->pcre_extra = pcre_study(f->pcre, 0, &err);
256 static int regex_read(void)
261 unsigned char *c = line_first(&in_line);
262 int n = line_count(&in_line);
269 int sep = pcre_exec(in_format->pcre, in_format->pcre_extra, (char *) c, n, i, 0, ovec, 3);
271 if (sep != PCRE_ERROR_NOMATCH)
272 warn(in_format, "PCRE matching error %d", sep);
273 // No further occurrence of the separator: the rest is a single field
275 in_field->len = n - i;
279 in_field->len = ovec[0] - i;
286 static void trim_fields(void)
288 unsigned char *line = line_first(&in_line);
289 for (int i = 0; i < fields_count(&in_fields); i++) {
290 struct field *f = fields_nth(&in_fields, i);
291 while (f->len && is_ws(line[f->start_pos]))
292 f->start_pos++, f->len--;
293 while (f->len && is_ws(line[f->start_pos + f->len - 1]))
298 /*** Field selection ***/
301 int first_field, last_field;
304 DECLARE_BUF(selectors, struct selector);
305 static selectors_t selectors;
307 static char *parse_selector(char *str)
309 char buf[strlen(str) + 1];
312 struct selector *s = selectors_push(&selectors);
313 char *sep = strchr(buf, '-');
316 s->first_field = atoi(buf);
317 s->last_field = atoi(sep);
319 s->first_field = s->last_field = atoi(buf);
324 static void finish_parse_selectors(void)
326 if (!selectors_count(&selectors))
330 static void select_fields(void)
332 for (int i = 0; i < selectors_count(&selectors); i++) {
333 struct selector *s = selectors_nth(&selectors, i);
334 int first = s->first_field;
337 int last = s->last_field;
339 last = fields_count(&in_fields);
340 for (int j = first; j <= last; j++) {
341 struct field *f = fields_push(&out_fields);
342 if (j >= 1 && j <= fields_count(&in_fields))
343 *f = *fields_nth(&in_fields, j-1);
345 f->start_pos = f->len = 0;
350 /*** Parsing of arguments ***/
352 static void usage(void)
355 Usage: xsv <in-format> [<out-format>] <options> [<fields>]\n\
358 -t, --tsv TAB-separated values (default)\n\
359 -c, --csv Comma-separated values\n\
360 -w, --ws Values separated by arbitrary whitespace\n\
361 -r, --regex=<rx> Separator given by Perl regular expression (input only)\n\
363 Format parameters:\n\
364 -d, --fs=<char> Delimiter of fields\n\
365 -q, --quiet Do not show warnings\n\
366 --always-quote Put quotes around all fields (CSV output only)\n\
369 --trim Trim leading and trailing whitespaces in fields\n\
374 static void bad_args(const char *msg, ...)
379 fprintf(stderr, "xsv: ");
380 vfprintf(stderr, msg, args);
384 fprintf(stderr, "Try `xsv --help' for more information.\n");
388 static const char short_options[] = "cd:qr:tw";
396 static const struct option long_options[] = {
397 { "always-quote", 0, NULL, OPT_ALWAYS_QUOTE },
398 { "csv", 0, NULL, 'c' },
399 { "fs", 1, NULL, 'd' },
400 { "quiet", 0, NULL, 'q' },
401 { "regex", 1, NULL, 'r' },
402 { "trim", 0, NULL, OPT_TRIM },
403 { "tsv", 0, NULL, 't' },
404 { "ws", 0, NULL, 'w' },
405 { "help", 0, NULL, OPT_HELP },
406 { NULL, 0, NULL, 0 },
409 static void set_format(int format_id)
411 struct format *f = xmalloc(sizeof(*f));
412 memset(f, 0, sizeof(*f));
419 f->read_line = csv_read;
420 f->write_line = csv_write;
425 f->read_line = csv_read;
426 f->write_line = csv_write;
431 f->read_line = ws_read;
432 f->write_line = csv_write;
435 f->read_line = regex_read;
441 else if (!out_format)
444 bad_args("At most two format may be given.");
447 static struct format *current_format(void)
453 set_format(FORM_TSV);
457 int main(int argc, char **argv)
463 while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) >= 0)
466 set_format(FORM_CSV);
470 current_format()->fs = optarg[0];
472 bad_args("No field delimiter given.");
475 current_format()->quiet = 1;
478 set_format(FORM_REGEX);
479 err = regex_set(current_format(), optarg);
481 bad_args("Error compiling regex: %s", err);
484 set_format(FORM_TSV);
489 case OPT_ALWAYS_QUOTE:
490 if (current_format()->id != FORM_CSV)
491 bad_args("--always-quote makes sense only for CSV.");
492 current_format()->always_quote = 1;
505 out_format = in_format;
506 if (!in_format->read_line)
507 bad_args("Write-only format selected for input.");
508 if (!out_format->write_line)
509 bad_args("Read-only format selected for output.");
511 for (int i = optind; i < argc; i++) {
512 err = parse_selector(argv[i]);
516 finish_parse_selectors();
518 fields_init(&in_fields);
519 fields_init(&out_fields);
524 fields_reset(&in_fields);
525 line_reset(&in_line);
527 if (!in_format->read_line())
533 fields_reset(&out_fields);
536 out_format->write_line();