2 * A Swiss-Army Knife for CSV-like Files
4 * (c) 2012 Martin Mares <mj@ucw.cz>
19 /*** Memory allocation ***/
21 static void *xmalloc(size_t bytes)
23 void *p = malloc(bytes);
25 fprintf(stderr, "xsv: Out of memory (cannot allocate %zu bytes)\n", bytes);
31 static void *xmalloc_zero(size_t bytes)
33 void *p = xmalloc(bytes);
38 static void *xrealloc(void *old, size_t bytes)
40 void *p = realloc(old, bytes);
42 fprintf(stderr, "xsv: Out of memory (cannot allocate %zu bytes)\n", bytes);
48 #define DECLARE_BUF(name, type) \
49 typedef struct { type *start; int count; int max; } name##_t; \
50 static inline void name##_init(name##_t *b) { b->start = NULL; b->count = b->max = 0; } \
51 static inline void name##_reset(name##_t *b) { b->count = 0; } \
52 static inline int name##_count(name##_t *b) { return b->count; } \
53 static void name##_extend(name##_t *b) { \
54 b->max = b->max ? 2*b->max : 16; \
55 b->start = xrealloc(b->start, b->max * sizeof(type)); \
57 static inline type *name##_push(name##_t *b) { \
58 if (b->count >= b->max) name##_extend(b); \
59 return &b->start[b->count++]; \
61 static inline type *name##_first(name##_t *b) { return b->start; } \
62 static inline type *name##_nth(name##_t *b, int n) { return &b->start[n]; } \
65 DECLARE_BUF(intarray, int);
67 /*** Formats and their parameters ***/
84 int (*read_line)(void);
85 void (*write_line)(void);
96 pcre_extra *pcre_extra;
98 // Temporary file backend:
100 intarray_t column_widths;
106 static struct format *in_format, *out_format;
107 static int want_trim;
114 DECLARE_BUF(fields, struct field);
115 DECLARE_BUF(line, unsigned char);
117 static fields_t in_fields, out_fields;
118 static struct field *in_field;
119 static line_t in_line;
120 static int line_number;
122 static void new_field(int pos)
124 in_field = fields_push(&in_fields);
125 in_field->start_pos = pos;
129 static void ensure_field(int pos)
135 static void warn(struct format *fmt, char *msg, ...)
138 fprintf(stderr, "Warning at line %d: ", line_number);
141 vfprintf(stderr, msg, args);
147 static int next_line(void)
150 int c = getchar_unlocked();
154 return !!line_count(&in_line);
157 *line_push(&in_line) = c;
161 static int field_chars(struct field *f)
163 unsigned char *s = line_nth(&in_line, f->start_pos);
166 memset(&mbs, 0, sizeof(mbs));
170 size_t k = mbrlen((char *) s + i, f->len - i, &mbs);
180 /*** CSV/TSV back-end */
182 static int csv_read(void)
186 int c = getchar_unlocked();
187 int i = line_count(&in_line);
191 if (c < 0 || c == '\n') {
193 warn(in_format, "Missing closing quote.");
195 return !!fields_count(&in_fields);
200 if (c == in_format->quote) {
201 c = getchar_unlocked();
202 if (c != in_format->quote) {
206 // Two quotes assimilate to one
208 // Fall through to pushing the character
209 } else if (c == in_format->quote) {
212 } else if (c == in_format->fs && !quoted) {
218 *line_push(&in_line) = c;
223 static int is_ws(int c)
225 return (c == ' ' || c == '\t' || c == '\f');
228 static void csv_write(void)
230 unsigned char *line = line_first(&in_line);
231 int n = fields_count(&out_fields);
232 for (int i=0; i<n; i++) {
233 struct field *f = fields_nth(&out_fields, i);
235 if (out_format->quote >= 0) {
236 need_quotes = out_format->always_quote;
237 for (int j=0; !need_quotes && j < f->len; j++) {
238 int c = line[f->start_pos + j];
239 if (c == out_format->fs || c == out_format->quote)
244 putchar_unlocked(out_format->fs);
246 putchar_unlocked(out_format->quote);
247 for (int j=0; j < f->len; j++) {
248 int c = line[f->start_pos + j];
249 if (c == out_format->fs && !need_quotes)
250 warn(out_format, "Field separator found inside field and quoting is turned off.");
251 if (c == out_format->quote)
256 putchar_unlocked(out_format->quote);
258 putchar_unlocked('\n');
261 /*** White-space back-end ***/
263 static int ws_read(void)
268 unsigned char *line = line_first(&in_line);
269 int n = line_count(&in_line);
275 for (int i=0; i<n; i++) {
281 if (!in_field->start_pos &&
283 !in_format->strict_ws)
284 in_field->start_pos = i;
293 if (ws && in_format->strict_ws)
298 /*** Regex back-end ***/
300 static const char *regex_set(struct format *f, char *rx)
304 f->pcre = pcre_compile(rx, PCRE_DOLLAR_ENDONLY, &err, &errpos, NULL);
308 f->pcre_extra = pcre_study(f->pcre, 0, &err);
315 static int regex_read(void)
320 unsigned char *c = line_first(&in_line);
321 int n = line_count(&in_line);
328 int sep = pcre_exec(in_format->pcre, in_format->pcre_extra, (char *) c, n, i, 0, ovec, 3);
330 if (sep != PCRE_ERROR_NOMATCH)
331 warn(in_format, "PCRE matching error %d", sep);
332 // No further occurrence of the separator: the rest is a single field
334 in_field->len = n - i;
338 in_field->len = ovec[0] - i;
343 /*** Table back-end ***/
345 static void table_write(void)
347 for (int i = 0; i < fields_count(&in_fields); i++) {
349 printf("%*s", out_format->table_sep, "");
350 struct field *f = fields_nth(&in_fields, i);
351 int fw = field_chars(f);
352 int cw = *intarray_nth(&in_format->column_widths, i);
354 warn(out_format, "Internal error: Wrongly calculated column width (%d > %d)", fw, cw);
357 unsigned char *p = line_nth(&in_line, f->start_pos);
358 for (int j = 0; j < f->len; j++)
359 putchar_unlocked(p[j]);
361 putchar_unlocked(' ');
365 putchar_unlocked('\n');
368 /*** Temporary file back-end ***/
370 static int tmp_read(void)
372 FILE *tf = in_format->tmp_file;
375 int c = getc_unlocked(tf);
381 c = getc_unlocked(tf);
382 c = (c << 8) | getc_unlocked(tf);
383 c = (c << 8) | getc_unlocked(tf);
384 c = (c << 8) | getc_unlocked(tf);
386 new_field(line_count(&in_line));
389 int x = getc_unlocked(tf);
391 warn(in_format, "Truncated temporary file");
394 *line_push(&in_line) = x;
399 static void tmp_write(void)
401 FILE *tf = out_format->tmp_file;
403 for (int i = 0; i < fields_count(&in_fields); i++) {
404 struct field *f = fields_nth(&in_fields, i);
406 putc_unlocked(f->len, tf);
408 putc_unlocked(0xfe, tf);
409 putc_unlocked((f->len >> 24) & 0xff, tf);
410 putc_unlocked((f->len >> 16) & 0xff, tf);
411 putc_unlocked((f->len >> 8) & 0xff, tf);
412 putc_unlocked(f->len & 0xff, tf);
415 unsigned char *p = line_nth(&in_line, f->start_pos);
416 for (int j = 0; j < f->len; j++)
417 putc_unlocked(*p++, tf);
419 intarray_t *w = &out_format->column_widths;
420 while (i >= intarray_count(w))
421 *intarray_push(w) = 0;
422 int fw = field_chars(f);
423 if (*intarray_nth(w, i) < fw)
424 *intarray_nth(w, i) = fw;
426 putc_unlocked(0xff, tf);
431 static void trim_fields(void)
433 unsigned char *line = line_first(&in_line);
434 for (int i = 0; i < fields_count(&in_fields); i++) {
435 struct field *f = fields_nth(&in_fields, i);
436 while (f->len && is_ws(line[f->start_pos]))
437 f->start_pos++, f->len--;
438 while (f->len && is_ws(line[f->start_pos + f->len - 1]))
443 /*** Field selection ***/
446 int first_field, last_field;
449 DECLARE_BUF(selectors, struct selector);
450 static selectors_t selectors;
452 static char *parse_selector(char *str)
454 char buf[strlen(str) + 1];
457 struct selector *s = selectors_push(&selectors);
458 char *sep = strchr(buf, '-');
461 s->first_field = atoi(buf);
462 s->last_field = atoi(sep);
464 s->first_field = s->last_field = atoi(buf);
469 static void finish_parse_selectors(void)
471 if (!selectors_count(&selectors))
475 static void select_fields(void)
477 for (int i = 0; i < selectors_count(&selectors); i++) {
478 struct selector *s = selectors_nth(&selectors, i);
479 int first = s->first_field;
482 int last = s->last_field;
484 last = fields_count(&in_fields);
485 for (int j = first; j <= last; j++) {
486 struct field *f = fields_push(&out_fields);
487 if (j >= 1 && j <= fields_count(&in_fields))
488 *f = *fields_nth(&in_fields, j-1);
490 f->start_pos = f->len = 0;
495 /*** Processing of files ***/
497 static void one_pass(void)
502 fields_reset(&in_fields);
503 line_reset(&in_line);
505 if (!in_format->read_line())
511 fields_reset(&out_fields);
514 out_format->write_line();
518 static void two_pass(void)
520 struct format *final_format = out_format;
522 // We need to use character set info from the current locale
523 setlocale(LC_CTYPE, "");
525 // Pass 1: Set up writer of intermediate format
526 out_format = xmalloc_zero(sizeof(*out_format));
527 out_format->id = FORM_TMP;
528 out_format->read_line = tmp_read;
529 out_format->write_line = tmp_write;
530 out_format->tmp_file = tmpfile();
531 intarray_init(&out_format->column_widths);
534 // Pass 2: Set up reader of intermediate format
535 in_format = out_format;
536 rewind(in_format->tmp_file);
537 out_format = final_format;
539 fclose(in_format->tmp_file);
542 /*** Parsing of arguments ***/
544 static void usage(void)
547 Usage: xsv <in-format> [<out-format>] <options> [<fields>]\n\
550 -t, --tsv TAB-separated values (default)\n\
551 -c, --csv Comma-separated values\n\
552 -w, --ws Values separated by arbitrary whitespace\n\
553 -W, --strict-ws Like --ws, but recognize empty columns at start/end\n\
554 -r, --regex=<rx> Separator given by Perl regular expression (input only)\n\
555 --table Format a table (output only)\n\
557 Format parameters:\n\
558 -d, --fs=<char> Delimiter of fields\n\
559 -q, --quiet Do not show warnings\n\
560 --always-quote Put quotes around all fields (CSV output only)\n\
561 --table-sep=<n> Separate table columns by <n> spaces (default: 2)\n\
564 --trim Trim leading and trailing whitespaces in fields\n\
569 static void bad_args(const char *msg, ...)
574 fprintf(stderr, "xsv: ");
575 vfprintf(stderr, msg, args);
579 fprintf(stderr, "Try `xsv --help' for more information.\n");
583 static const char short_options[] = "cd:qr:twW";
593 static const struct option long_options[] = {
594 { "always-quote", 0, NULL, OPT_ALWAYS_QUOTE },
595 { "csv", 0, NULL, 'c' },
596 { "fs", 1, NULL, 'd' },
597 { "quiet", 0, NULL, 'q' },
598 { "regex", 1, NULL, 'r' },
599 { "strict-ws", 0, NULL, 'W' },
600 { "table", 0, NULL, OPT_TABLE },
601 { "table-sep", 1, NULL, OPT_TABLE_SEP },
602 { "trim", 0, NULL, OPT_TRIM },
603 { "tsv", 0, NULL, 't' },
604 { "ws", 0, NULL, 'w' },
605 { "help", 0, NULL, OPT_HELP },
606 { NULL, 0, NULL, 0 },
609 static void set_format(int format_id)
611 struct format *f = xmalloc_zero(sizeof(*f));
618 f->read_line = csv_read;
619 f->write_line = csv_write;
624 f->read_line = csv_read;
625 f->write_line = csv_write;
630 f->read_line = ws_read;
631 f->write_line = csv_write;
634 f->read_line = regex_read;
637 f->write_line = table_write;
638 f->needs_two_passes = 1;
645 else if (!out_format)
648 bad_args("At most two formats may be given.");
651 static struct format *current_format(void)
657 set_format(FORM_TSV);
661 int main(int argc, char **argv)
666 while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) >= 0)
669 set_format(FORM_CSV);
673 current_format()->fs = optarg[0];
675 bad_args("No field delimiter given.");
678 current_format()->quiet = 1;
681 set_format(FORM_REGEX);
682 err = regex_set(current_format(), optarg);
684 bad_args("Error compiling regex: %s", err);
687 set_format(FORM_TSV);
694 current_format()->strict_ws = 1;
696 case OPT_ALWAYS_QUOTE:
697 if (current_format()->id != FORM_CSV)
698 bad_args("--always-quote makes sense only for CSV.");
699 current_format()->always_quote = 1;
707 set_format(FORM_TABLE);
710 current_format()->table_sep = atoi(optarg);
718 out_format = in_format;
719 if (!in_format->read_line)
720 bad_args("Write-only format selected for input.");
721 if (!out_format->write_line)
722 bad_args("Read-only format selected for output.");
724 for (int i = optind; i < argc; i++) {
725 err = parse_selector(argv[i]);
729 finish_parse_selectors();
731 fields_init(&in_fields);
732 fields_init(&out_fields);
735 if (out_format->needs_two_passes)