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(void)
95 in_field = fields_push(&in_fields);
96 in_field->start_pos = line_count(&in_line);
100 static void ensure_field(void)
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)
140 if (c < 0 || c == '\n') {
142 warn(in_format, "Missing closing quote.");
144 return !!fields_count(&in_fields);
149 if (c == in_format->quote) {
151 if (c != in_format->quote) {
155 // Two quotes assimilate to one
157 // Fall through to pushing the character
158 } else if (c == in_format->quote) {
161 } else if (c == in_format->fs && !quoted) {
167 *line_push(&in_line) = c;
172 static int is_ws(int c)
174 return (c == ' ' || c == '\t' || c == '\f');
177 static void csv_write(void)
179 unsigned char *line = line_first(&in_line);
180 int n = fields_count(&out_fields);
181 for (int i=0; i<n; i++) {
182 struct field *f = fields_nth(&out_fields, i);
184 if (out_format->quote >= 0) {
185 need_quotes = out_format->always_quote;
186 for (int j=0; !need_quotes && j < f->len; j++) {
187 int c = line[f->start_pos + j];
188 if (c == out_format->fs || c == out_format->quote)
193 putchar(out_format->fs);
195 putchar(out_format->quote);
196 for (int j=0; j < f->len; j++) {
197 int c = line[f->start_pos + j];
198 if (c == out_format->fs && !need_quotes)
199 warn(out_format, "Field separator found inside field and quoting is turned off.");
200 if (c == out_format->quote)
205 putchar(out_format->quote);
210 static int ws_read(void)
216 return !!fields_count(&in_fields);
228 *line_push(&in_line) = c;
235 static const char *regex_set(struct format *f, char *rx)
239 f->pcre = pcre_compile(rx, PCRE_DOLLAR_ENDONLY, &err, &errpos, NULL);
243 f->pcre_extra = pcre_study(f->pcre, 0, &err);
250 static int regex_read(void)
255 unsigned char *c = line_first(&in_line);
256 int n = line_count(&in_line);
263 int sep = pcre_exec(in_format->pcre, in_format->pcre_extra, (char *) c, n, i, 0, ovec, 3);
265 if (sep != PCRE_ERROR_NOMATCH)
266 warn(in_format, "PCRE matching error %d", sep);
267 // No further occurrence of the separator: the rest is a single field
269 in_field->start_pos = i;
270 in_field->len = n - i;
274 in_field->start_pos = i;
275 in_field->len = ovec[0] - i;
282 static void trim_fields(void)
284 unsigned char *line = line_first(&in_line);
285 for (int i = 0; i < fields_count(&in_fields); i++) {
286 struct field *f = fields_nth(&in_fields, i);
287 while (f->len && is_ws(line[f->start_pos]))
288 f->start_pos++, f->len--;
289 while (f->len && is_ws(line[f->start_pos + f->len - 1]))
294 /*** Field selection ***/
297 int first_field, last_field;
300 DECLARE_BUF(selectors, struct selector);
301 static selectors_t selectors;
303 static char *parse_selector(char *str)
305 char buf[strlen(str) + 1];
308 struct selector *s = selectors_push(&selectors);
309 char *sep = strchr(buf, '-');
312 s->first_field = atoi(buf);
313 s->last_field = atoi(sep);
315 s->first_field = s->last_field = atoi(buf);
320 static void finish_parse_selectors(void)
322 if (!selectors_count(&selectors))
326 static void select_fields(void)
328 for (int i = 0; i < selectors_count(&selectors); i++) {
329 struct selector *s = selectors_nth(&selectors, i);
330 int first = s->first_field;
333 int last = s->last_field;
335 last = fields_count(&in_fields);
336 for (int j = first; j <= last; j++) {
337 struct field *f = fields_push(&out_fields);
338 if (j >= 1 && j <= fields_count(&in_fields))
339 *f = *fields_nth(&in_fields, j-1);
341 f->start_pos = f->len = 0;
346 /*** Parsing of arguments ***/
348 static void usage(void)
351 Usage: xsv <in-format> [<out-format>] <options> [<fields>]\n\
354 -t, --tsv TAB-separated values (default)\n\
355 -c, --csv Comma-separated values\n\
356 -w, --ws Values separated by arbitrary whitespace\n\
357 -r, --regex=<rx> Separator given by Perl regular expression (input only)\n\
359 Format parameters:\n\
360 -d, --fs=<char> Delimiter of fields\n\
361 -q, --quiet Do not show warnings\n\
362 --always-quote Put quotes around all fields (CSV output only)\n\
365 --trim Trim leading and trailing whitespaces in fields\n\
370 static void bad_args(const char *msg, ...)
375 fprintf(stderr, "xsv: ");
376 vfprintf(stderr, msg, args);
380 fprintf(stderr, "Try `xsv --help' for more information.\n");
384 static const char short_options[] = "cd:qr:tw";
392 static const struct option long_options[] = {
393 { "always-quote", 0, NULL, OPT_ALWAYS_QUOTE },
394 { "csv", 0, NULL, 'c' },
395 { "fs", 1, NULL, 'd' },
396 { "quiet", 0, NULL, 'q' },
397 { "regex", 1, NULL, 'r' },
398 { "trim", 0, NULL, OPT_TRIM },
399 { "tsv", 0, NULL, 't' },
400 { "ws", 0, NULL, 'w' },
401 { "help", 0, NULL, OPT_HELP },
402 { NULL, 0, NULL, 0 },
405 static void set_format(int format_id)
407 struct format *f = xmalloc(sizeof(*f));
408 memset(f, 0, sizeof(*f));
415 f->read_line = csv_read;
416 f->write_line = csv_write;
421 f->read_line = csv_read;
422 f->write_line = csv_write;
427 f->read_line = ws_read;
428 f->write_line = csv_write;
431 f->read_line = regex_read;
437 else if (!out_format)
440 bad_args("At most two format may be given.");
443 static struct format *current_format(void)
449 set_format(FORM_TSV);
453 int main(int argc, char **argv)
459 while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) >= 0)
462 set_format(FORM_CSV);
466 current_format()->fs = optarg[0];
468 bad_args("No field delimiter given.");
471 current_format()->quiet = 1;
474 set_format(FORM_REGEX);
475 err = regex_set(current_format(), optarg);
477 bad_args("Error compiling regex: %s", err);
480 set_format(FORM_TSV);
485 case OPT_ALWAYS_QUOTE:
486 if (current_format()->id != FORM_CSV)
487 bad_args("--always-quote makes sense only for CSV.");
488 current_format()->always_quote = 1;
501 out_format = in_format;
502 if (!in_format->read_line)
503 bad_args("Write-only format selected for input.");
504 if (!out_format->write_line)
505 bad_args("Read-only format selected for output.");
507 for (int i = optind; i < argc; i++) {
508 err = parse_selector(argv[i]);
512 finish_parse_selectors();
514 fields_init(&in_fields);
515 fields_init(&out_fields);
520 fields_reset(&in_fields);
521 line_reset(&in_line);
523 if (!in_format->read_line())
529 fields_reset(&out_fields);
532 out_format->write_line();