-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcsv_tool.cpp
1615 lines (1339 loc) · 35.5 KB
/
csv_tool.cpp
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <errno.h>
#include <vector>
#include <regex.h>
#include <tr1/unordered_set>
#include "output_buffer.h"
#include "csv_reader.h"
#define CSV_TOOL_VERSION "20140829"
enum {
NO_HEADERLINE,
RE_NOCASE,
RE_INVERT,
UNIQ_COLS,
EXTRACT_ZERO,
};
class csv_tool
{
private:
char sep;
char sep_out;
char quot;
unsigned line_max;
public:
unsigned csv_flags;
private:
#define HAS_FLAG(f) ( csv_flags & ( 1 << f ) )
output_buffer *outbuf;
csv_reader *reader;
std::vector<std::string> *headers;
std::vector<int> indexes;
std::vector< std::vector<unsigned> > inv_indexes;
unsigned max_index;
std::string out_colspec;
void cleanup ( )
{
if ( reader )
{
delete reader;
reader = NULL;
}
if ( headers )
{
delete headers;
headers = NULL;
}
indexes.clear();
inv_indexes.clear();
out_colspec.clear();
}
void count_max_index ( )
{
if ( headers )
{
max_index = headers->size();
return;
}
// count columns on the current row
char *ptr = NULL;
unsigned len = 0;
max_index = 0;
while ( reader->read_csv_field( &ptr, &len ) )
++max_index;
// reset internal ptr for subsequent read_csv_fields
reader->reset_cur_field_offset();
}
// parse an unsigned long long
// return 0 on invalid character
// handle 0x prefix
int str_ull( const std::string &str, unsigned long long *ret ) const
{
*ret = 0;
if ( str.size() > 2 && str[0] == '0' && str[1] == 'x' )
{
for ( unsigned i = 2 ; i < str.size() ; ++i )
{
if ( (*ret >> 60) > 0 )
return 0;
else if ( str[i] >= '0' && str[i] <= '9' )
*ret = *ret * 16 + (str[i] - '0');
else if ( str[i] >= 'A' && str[i] <= 'F' )
*ret = *ret * 16 + (str[i] - 'A' + 10);
else if ( str[i] >= 'a' && str[i] <= 'f' )
*ret = *ret * 16 + (str[i] - 'a' + 10);
else
return 0;
}
}
else
{
for ( unsigned i = 0 ; i < str.size() ; ++i )
{
if ( (*ret >> 60) > 0 )
return 0;
else if ( str[i] >= '0' && str[i] <= '9' )
*ret = *ret * 10 + (str[i] - '0');
else
return 0;
}
}
return 1;
}
int str_ul( const std::string &str, unsigned long *ret ) const
{
unsigned long long ull;
*ret = 0;
if ( ! str_ull( str, &ull ) )
return 0;
if ( (ull >> 32) > 0 )
return 0;
*ret = (unsigned long)ull;
return 1;
}
// return the index of the string str in the string vector headers (case insensitive)
// checks for numeric indexes if not found (decimal, [0-9]+), < max_index
// return -1 if not found
int parse_index_uint( const std::string &str ) const
{
if ( str.size() == 0 )
return -1;
if ( headers )
for ( unsigned i = 0 ; i < headers->size() ; ++i )
if ( ! strcasecmp( str.c_str(), (*headers)[ i ].c_str() ) )
return i;
unsigned long ret;
if ( ! str_ul( str, &ret ) )
return -1;
if ( ret < max_index )
return ret;
return -1;
}
// Parse a colspec string (coma-separated list of column names), populate 'indexes'
//
// colspec is a coma-separated list of column names, or a coma-separated list of column indexes (numeric, 0-based)
// colspec may include ranges of columns, with "begin-end". Omit "begin" to start at 0, omit "end" to finish at last column.
//
// if a column is not found, its index is set as -1. For ranges, if begin or end is not found, add a single -1 index.
// without a header list, the current line is parsed and reset to count the fields per row
//
// populates out_colspec with the expanded ranges, keeps colnames (including unknown cols) when possible
void parse_colspec( const std::string &colspec_str )
{
// parse colspec_str: split on comas
std::vector<std::string> colspec_vec;
if ( colspec_str.size() > 0 )
{
size_t off = 0, idx = -1;
while ( (idx = colspec_str.find( ',', off )) != std::string::npos )
{
colspec_vec.push_back( colspec_str.substr( off, idx-off ) );
off = idx + 1;
}
colspec_vec.push_back( colspec_str.substr( off ) );
}
// uniq_cols stuff: list colnames directly specified in colspec
std::vector<int> direct_cols;
if ( HAS_FLAG( UNIQ_COLS ) )
for ( unsigned i = 0 ; i < colspec_vec.size() ; ++i )
{
int idx = parse_index_uint( colspec_vec[ i ] );
if ( idx >= 0 )
direct_cols.push_back( idx );
}
// generate indexes, handle ranges in colspec_vec
for ( unsigned i = 0 ; i < colspec_vec.size() ; ++i )
{
int idx = parse_index_uint( colspec_vec[ i ] );
if ( idx != -1 )
{
indexes.push_back( idx );
if ( i > 0 )
out_colspec.push_back( ',' );
out_colspec.append( colspec_vec[ i ] );
}
else
{
// check for ranges
// handle col names including '-'
size_t dash_off = -1;
while (1)
{
dash_off = colspec_vec[ i ].find( '-', dash_off + 1 );
if ( dash_off == std::string::npos )
{
std::cerr << "Column not found: " << colspec_vec[ i ] << std::endl;
indexes.push_back( -1 );
if ( i > 0 )
out_colspec.push_back( ',' );
out_colspec.append( colspec_vec[ i ] );
break;
}
int min, max;
if ( dash_off == 0 )
min = 0;
else
min = parse_index_uint( colspec_vec[ i ].substr( 0, dash_off ) );
if ( dash_off == colspec_vec[ i ].size() - 1 )
max = max_index - 1;
else
max = parse_index_uint( colspec_vec[ i ].substr( dash_off + 1 ) );
if ( min >= 0 && max >= 0 )
{
for ( int range_idx = min ; range_idx <= max ; ++range_idx )
{
bool in_direct = false;
for ( unsigned j = 0 ; j < direct_cols.size() ; ++j )
if ( direct_cols[ j ] == range_idx )
in_direct = true;
if ( ! in_direct )
{
indexes.push_back( range_idx );
if ( out_colspec.size() > 0 )
out_colspec.push_back( ',' );
if ( headers && (unsigned)range_idx < headers->size() )
out_colspec.append( (*headers)[ range_idx ] );
else
out_colspec.append( ull_str( range_idx ) );
}
}
break;
}
}
}
}
// inv[ input col idx ] = [ out col idx, out col idx ]
inv_indexes.resize( max_index );
for ( unsigned idx_out = 0 ; idx_out < indexes.size() ; ++idx_out )
{
int idx_in = indexes[ idx_out ];
if ( idx_in == -1 )
continue;
inv_indexes[ idx_in ].push_back( idx_out );
}
}
// create a csv reader, populate indexes from colspec
// returns true if everything is fine
bool start_reader ( const std::string &colspec, const char *filename )
{
cleanup();
reader = new csv_reader( filename, sep, quot, line_max );
if ( reader->failed_to_open() )
{
cleanup();
return false;
}
if ( ! HAS_FLAG( NO_HEADERLINE ) )
{
if ( ! reader->fetch_line() )
{
cleanup();
return false;
}
headers = reader->parse_line();
}
reader->fetch_line();
count_max_index();
parse_colspec( colspec );
return true;
}
// split a string "k1=v1,k2=v2,k3=v3" into vectors [k1, k2, k3] and [v1, v2, v3]
// k may be omitted with -H
bool split_colvalspec( const std::string &colval, std::vector<std::string> *cols, std::vector<std::string> *vals )
{
size_t off = 0;
while (1)
{
size_t eq_off = colval.find( '=', off );
if ( eq_off == std::string::npos )
{
if ( ! HAS_FLAG( NO_HEADERLINE ) )
{
std::cerr << "Invalid colval: no '=' after " << colval.substr( off ) << std::endl;
return false;
}
cols->push_back( colval.substr( 0, 0 ) );
}
else
{
cols->push_back( colval.substr( off, eq_off - off ) );
off = eq_off + 1;
}
size_t next_off = colval.find( ',', off );
if ( next_off == std::string::npos )
{
vals->push_back( colval.substr( off ) );
return true;
}
vals->push_back( colval.substr( off, next_off - off ) );
off = next_off + 1;
}
}
std::string ull_str ( const unsigned long long nr, const char *fmt = "%llu" )
{
char buf[16];
unsigned buf_sz = snprintf( buf, sizeof(buf), fmt, nr );
if ( buf_sz > sizeof(buf) )
buf_sz = sizeof(buf);
std::string ret( buf, buf_sz );
return ret;
}
std::string str_downcase( const std::string &str )
{
std::string ret;
for ( unsigned i = 0 ; i < str.size() ; ++i )
ret.push_back( tolower( str[ i ] ) );
return ret;
}
public:
explicit csv_tool ( output_buffer *outbuf, char sep = ',', char sep_out = ',', char quot = '"', unsigned line_max = 64*1024, unsigned csv_flags = 0 ) :
sep(sep),
sep_out(sep_out),
quot(quot),
line_max(line_max),
csv_flags(csv_flags),
outbuf(outbuf),
reader(NULL),
headers(NULL),
max_index(0)
{
indexes.clear();
inv_indexes.clear();
out_colspec.clear();
}
~csv_tool ( )
{
cleanup();
}
// read one column name (specified in colspec), and dump to outbuf every unescaped row field content for this column
void extract ( const std::string &colspec, const char *filename )
{
if ( ! start_reader( colspec, filename ) )
return;
if ( indexes.size() != 1 || indexes[0] < 0 )
{
std::cerr << "Invalid colspec" << std::endl;
return;
}
if ( reader->eos() )
return;
int zero = 0;
if ( HAS_FLAG( EXTRACT_ZERO ) )
zero = 1; // lol!
do
{
char *ptr = NULL;
unsigned len = 0;
unsigned idx_in = 0;
while ( reader->read_csv_field( &ptr, &len ) )
{
if ( ( idx_in < inv_indexes.size() ) && ( inv_indexes[ idx_in ].size() > 0 ) )
{
std::string *str = reader->unescape_csv_field( &ptr, &len );
if ( str )
{
outbuf->append( str );
delete str;
}
else
outbuf->append( ptr, len );
}
// cannot break: a later field may include a newline
++idx_in;
}
if ( zero )
outbuf->append( '\0' );
else
outbuf->append_nl();
} while ( reader->fetch_line() );
}
// output a csv containing the columns from colspec of the input csv
// return the expanded colspec used for the file (to reuse for next files)
std::string select ( const std::string &colspec, const char *filename, bool show_headers )
{
if ( ! start_reader( colspec, filename ) )
return out_colspec;
if ( show_headers && headers )
{
for ( unsigned i = 0 ; i < indexes.size() ; ++i )
{
if ( i > 0 )
outbuf->append( sep_out );
int idx_in = indexes[ i ];
if ( idx_in != -1 )
outbuf->append( reader->escape_csv_field( (*headers)[ idx_in ] ) );
}
outbuf->append_nl();
}
if ( reader->eos() )
return out_colspec;
unsigned idx_len = indexes.size();
unsigned *fld_off = new unsigned[ idx_len ];
unsigned *fld_len = new unsigned[ idx_len ];
const bool may_need_escape = ( sep_out != sep );
do
{
for ( unsigned idx_out = 0 ; idx_out < idx_len ; ++idx_out )
fld_off[ idx_out ] = (unsigned)-1;
// parse input row
char *line = NULL;
unsigned f_off = 0, f_len = 0;
unsigned idx_in = 0;
while ( reader->read_csv_field( &line, &f_off, &f_len ) )
{
if ( idx_in < inv_indexes.size() && inv_indexes[ idx_in ].size() )
{
// current input field appears in output, save its off+len
for ( unsigned i = 0 ; i < inv_indexes[ idx_in ].size() ; ++i )
{
unsigned idx_out = inv_indexes[ idx_in ][ i ];
fld_off[ idx_out ] = f_off;
fld_len[ idx_out ] = f_len;
}
}
++idx_in;
}
// generate output row
for ( unsigned idx_out = 0 ; idx_out < idx_len ; ++idx_out )
{
if ( idx_out > 0 )
outbuf->append( sep_out );
if ( fld_off[ idx_out ] != (unsigned)-1 )
{
if ( may_need_escape && fld_len[ idx_out ] && ( line[ fld_off[ idx_out ] ] != quot ) )
{
std::string raw_f( line + fld_off[ idx_out ], fld_len[ idx_out ] );
outbuf->append( reader->escape_csv_field( raw_f ) );
} else
outbuf->append( line + fld_off[ idx_out ], fld_len[ idx_out ] );
}
}
outbuf->append_nl();
} while ( reader->fetch_line() );
delete[] fld_off;
delete[] fld_len;
return out_colspec;
}
// output a csv with some columns removed
void deselect ( const std::string &colspec, const char *filename )
{
if ( ! start_reader( colspec, filename ) )
return;
if ( headers )
{
unsigned colnum_out = 0;
for ( unsigned i = 0 ; i < headers->size() ; ++i )
{
if ( inv_indexes[ i ].size() )
continue;
if ( colnum_out++ > 0 )
outbuf->append( sep_out );
outbuf->append( reader->escape_csv_field( (*headers)[ i ] ) );
++colnum_out;
}
outbuf->append_nl();
}
if ( reader->eos() )
return;
do
{
char *fld = NULL;
unsigned fld_len = 0;
unsigned colnum = 0;
unsigned colnum_out = 0;
while ( reader->read_csv_field( &fld, &fld_len ) )
{
if ( inv_indexes[ colnum++ ].size() )
continue;
if ( colnum_out++ > 0 )
outbuf->append( sep_out );
outbuf->append( fld, fld_len );
}
outbuf->append_nl();
} while ( reader->fetch_line() );
}
// list columns of the file (indexes if -H)
void listcol ( const char *filename )
{
if ( ! start_reader( "", filename ) )
return;
if ( headers )
{
for ( unsigned i = 0 ; i < headers->size() ; ++i )
{
outbuf->append( (*headers)[ i ] );
outbuf->append_nl();
}
}
else
{
for ( unsigned i = 0 ; i < max_index ; ++i )
{
outbuf->append( ull_str( i ) );
outbuf->append_nl();
}
}
}
// prepend fields to every row (ignore added colnames if -H)
void addcol ( const std::string &colval, const char *filename )
{
std::vector<std::string> cols;
std::vector<std::string> vals;
if ( ! split_colvalspec( colval, &cols, &vals ) )
return;
if ( ! start_reader( "", filename ) )
return;
if ( headers )
{
for ( unsigned i = 0 ; i < cols.size() ; ++i )
{
outbuf->append( reader->escape_csv_field( cols[i] ) );
outbuf->append( sep_out );
}
for ( unsigned i = 0 ; i < headers->size() ; ++i )
{
outbuf->append( reader->escape_csv_field( (*headers)[i] ) );
if ( i + 1 < headers->size() )
outbuf->append( sep_out );
}
outbuf->append_nl();
}
if ( reader->eos() )
return;
do
{
for ( unsigned i = 0 ; i < vals.size() ; ++i )
{
if ( i > 0 )
outbuf->append( sep_out );
outbuf->append( vals[ i ] );
}
char *fld = NULL;
unsigned fld_len = 0;
while ( reader->read_csv_field( &fld, &fld_len ) )
{
outbuf->append( sep_out );
outbuf->append( fld, fld_len );
}
outbuf->append_nl();
} while ( reader->fetch_line() );
}
// filter csv, display only lines whose field value match a regexp
void grepcol ( const std::string &colval, const char *filename )
{
std::vector<std::string> cols;
std::vector<std::string> vals;
if ( ! split_colvalspec( colval, &cols, &vals ) )
return;
// merge cols in a colspec
std::string colspec;
for ( unsigned i = 0 ; i < cols.size() ; ++i )
{
if ( i > 0 )
colspec.push_back( ',' );
colspec.append( cols[ i ] );
}
regex_t *vals_re = new regex_t[ vals.size() ];
int flags = REG_NOSUB | REG_EXTENDED;
if ( HAS_FLAG( RE_NOCASE ) )
flags |= REG_ICASE;
for ( unsigned i = 0 ; i < vals.size() ; ++i )
{
int err = regcomp( &vals_re[ i ], vals[ i ].c_str(), flags );
if ( err )
{
char errbuf[1024];
regerror( err, &vals_re[ i ], errbuf, sizeof(errbuf) );
std::cerr << "Invalid regexp /" << vals[ i ] << "/ : " << errbuf << std::endl;
for ( unsigned j = 0 ; j < i ; ++j )
regfree( &vals_re[ j ] );
delete[] vals_re;
return;
}
}
if ( ! start_reader( colspec, filename ) )
{
for ( unsigned i = 0 ; i < vals.size() ; ++i )
regfree( &vals_re[ i ] );
delete[] vals_re;
return;
}
if ( headers )
{
for ( unsigned i = 0 ; i < headers->size() ; ++i )
{
if ( i > 0 )
outbuf->append( sep_out );
outbuf->append( reader->escape_csv_field( (*headers)[i] ) );
}
outbuf->append_nl();
}
if ( reader->eos() )
{
for ( unsigned i = 0 ; i < vals.size() ; ++i )
regfree( &vals_re[ i ] );
delete[] vals_re;
return;
}
const unsigned stats_batch_size = 16*1024;
unsigned stats_seen = 0;
unsigned stats_match = (headers ? 1 : 0);
bool invert = HAS_FLAG( RE_INVERT );
do
{
char *line = NULL;
unsigned f_off = 0, f_len = 0;
unsigned idx_in = 0;
bool show = false;
while ( reader->read_csv_field( &line, &f_off, &f_len ) )
{
if ( ( idx_in < inv_indexes.size() ) && ( inv_indexes[ idx_in ].size() ) )
{
std::string str;
char *ptr = line + f_off;
unsigned len = f_len;
reader->unescape_csv_field( &ptr, &len, &str );
for ( unsigned i = 0 ; i < inv_indexes[ idx_in ].size() ; ++i )
{
unsigned idx_g = inv_indexes[ idx_in ][ i ];
if ( idx_g < vals.size() && regexec( &vals_re[ idx_g ], str.c_str(), 0, NULL, 0 ) != REG_NOMATCH )
show = true;
}
}
++idx_in;
}
if ( show ^ invert )
{
outbuf->append( line, f_off + f_len );
outbuf->append_nl();
++stats_match;
}
++stats_seen;
// manually flush if output is sparse
if ( stats_seen > stats_batch_size )
{
if ( ( stats_match > 0 ) && ( stats_match < stats_batch_size / 8 ) )
outbuf->flush();
stats_seen = 0;
// ensure we'll flush next time if we didnt now and next is empty
stats_match = ( ( stats_match >= stats_batch_size / 8 ) ? 1 : 0 );
}
} while ( reader->fetch_line() );
for ( unsigned i = 0 ; i < vals.size() ; ++i )
regfree( &vals_re[ i ] );
delete[] vals_re;
}
// filter csv, display only lines whose field appears on a file line
void fgrepcol ( const std::string &colval, const char *filename )
{
std::vector<std::string> cols;
std::vector<std::string> vals;
if ( ! split_colvalspec( colval, &cols, &vals ) )
return;
// merge cols in a colspec
std::string colspec;
for ( unsigned i = 0 ; i < cols.size() ; ++i )
{
if ( i > 0 )
colspec.push_back( ',' );
colspec.append( cols[ i ] );
}
std::tr1::unordered_set<std::string> *vals_set = new std::tr1::unordered_set<std::string>[ vals.size() ];
bool nocase = HAS_FLAG( RE_NOCASE );
for ( unsigned i = 0 ; i < vals.size() ; ++i )
{
std::string line;
std::ifstream in(vals[ i ].c_str());
if ( ! in )
{
std::cerr << "Cannot open " << vals[ i ] << ": " << strerror( errno ) << std::endl;
delete[] vals_set;
return;
}
while ( std::getline( in, line ) )
{
if ( line.size() > 0 && line[ line.size() - 1 ] == '\n' )
line.erase( line.size() - 1 );
if ( line.size() > 0 && line[ line.size() - 1 ] == '\r' )
line.erase( line.size() - 1 );
if ( nocase )
vals_set[ i ].insert( str_downcase( line ) );
else
vals_set[ i ].insert( line );
}
}
if ( ! start_reader( colspec, filename ) )
{
delete[] vals_set;
return;
}
if ( headers )
{
for ( unsigned i = 0 ; i < headers->size() ; ++i )
{
if ( i > 0 )
outbuf->append( sep_out );
outbuf->append( reader->escape_csv_field( (*headers)[i] ) );
}
outbuf->append_nl();
}
if ( reader->eos() )
{
delete[] vals_set;
return;
}
const unsigned stats_batch_size = 16*1024;
unsigned stats_seen = 0;
unsigned stats_match = (headers ? 1 : 0);
bool invert = HAS_FLAG( RE_INVERT );
do
{
char *line = NULL;
unsigned f_off = 0, f_len = 0;
unsigned idx_in = 0;
bool show = false;
while ( reader->read_csv_field( &line, &f_off, &f_len ) )
{
if ( ( idx_in < inv_indexes.size() ) && inv_indexes[ idx_in ].size() )
{
std::string str;
char *ptr = line + f_off;
unsigned len = f_len;
reader->unescape_csv_field( &ptr, &len, &str );
for ( unsigned i = 0 ; i < inv_indexes[ idx_in ].size() ; ++i )
{
unsigned idx_g = inv_indexes[ idx_in ][ i ];
if ( idx_g >= vals.size() )
continue;
if ( nocase )
{
if ( vals_set[ idx_g ].count( str_downcase( str ) ) > 0 )
show = true;
}
else
{
if ( vals_set[ idx_g ].count( str ) > 0 )
show = true;
}
}
}
++idx_in;
}
if ( show ^ invert )
{
outbuf->append( line, f_off + f_len );
outbuf->append_nl();
++stats_match;
}
++stats_seen;
// manually flush if output is sparse
if ( stats_seen > stats_batch_size )
{
if ( ( stats_match > 0 ) && ( stats_match < stats_batch_size / 8 ) )
outbuf->flush();
stats_seen = 0;
// ensure we'll flush next time if we didnt now and next is empty
stats_match = ( ( stats_match >= stats_batch_size / 8 ) ? 1 : 0 );
}
} while ( reader->fetch_line() );
delete[] vals_set;
}
// output a csv containing the concatenation of the specified columns as last column
void concat ( const std::string &colspec, const char *filename )
{
if ( ! start_reader( colspec, filename ) )
return;
if ( headers )
{
for ( unsigned i = 0 ; i < headers->size() ; ++i )
{
if ( i > 0 )
outbuf->append( sep_out );
outbuf->append( reader->escape_csv_field( (*headers)[i] ) );
}
outbuf->append( sep_out );
outbuf->append( reader->escape_csv_field( "concat" ) );
outbuf->append_nl();
}
if ( reader->eos() )
return;
std::string *flds = new std::string[ inv_indexes.size() ];
std::string ccat;
do
{
char *line = NULL;
unsigned f_off = 0, f_len = 0;
unsigned idx_in = 0;
while ( reader->read_csv_field( &line, &f_off, &f_len ) )
{
if ( ( idx_in < inv_indexes.size() ) && ( inv_indexes[ idx_in ].size() ) )
{
flds[ idx_in ].clear();
char *ptr = line + f_off;
unsigned len = f_len;
reader->unescape_csv_field( &ptr, &len, &flds[ idx_in ] );
}
++idx_in;
}
outbuf->append( line, f_off + f_len );
outbuf->append( sep_out );
ccat.clear();
for ( unsigned i = 0 ; i < indexes.size() ; ++i )
if ( indexes[ i ] != -1 )
ccat += flds[ indexes[ i ] ];
outbuf->append( reader->escape_csv_field( ccat ) );
outbuf->append_nl();
} while ( reader->fetch_line() );
delete[] flds;
}