cut: fix -f to work with the -d$'\n' edge case
[platform/upstream/coreutils.git] / src / cut.c
1 /* cut - remove parts of lines of files
2    Copyright (C) 1997-2013 Free Software Foundation, Inc.
3    Copyright (C) 1984 David M. Ihnat
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Written by David Ihnat.  */
19
20 /* POSIX changes, bug fixes, long-named options, and cleanup
21    by David MacKenzie <djm@gnu.ai.mit.edu>.
22
23    Rewrite cut_fields and cut_bytes -- Jim Meyering.  */
24
25 #include <config.h>
26
27 #include <stdio.h>
28 #include <assert.h>
29 #include <getopt.h>
30 #include <sys/types.h>
31 #include "system.h"
32
33 #include "error.h"
34 #include "fadvise.h"
35 #include "getndelim2.h"
36 #include "hash.h"
37 #include "quote.h"
38 #include "xstrndup.h"
39
40 /* The official name of this program (e.g., no 'g' prefix).  */
41 #define PROGRAM_NAME "cut"
42
43 #define AUTHORS \
44   proper_name ("David M. Ihnat"), \
45   proper_name ("David MacKenzie"), \
46   proper_name ("Jim Meyering")
47
48 #define FATAL_ERROR(Message)                                            \
49   do                                                                    \
50     {                                                                   \
51       error (0, 0, (Message));                                          \
52       usage (EXIT_FAILURE);                                             \
53     }                                                                   \
54   while (0)
55
56 /* Append LOW, HIGH to the list RP of range pairs, allocating additional
57    space if necessary.  Update local variable N_RP.  When allocating,
58    update global variable N_RP_ALLOCATED.  */
59
60 #define ADD_RANGE_PAIR(rp, low, high)                   \
61   do                                                    \
62     {                                                   \
63       if (low == 0 || high == 0)                        \
64         FATAL_ERROR (_("fields and positions are numbered from 1")); \
65       if (n_rp >= n_rp_allocated)                       \
66         {                                               \
67           (rp) = X2NREALLOC (rp, &n_rp_allocated);      \
68         }                                               \
69       rp[n_rp].lo = (low);                              \
70       rp[n_rp].hi = (high);                             \
71       ++n_rp;                                           \
72     }                                                   \
73   while (0)
74
75 struct range_pair
76   {
77     size_t lo;
78     size_t hi;
79   };
80
81 /* This buffer is used to support the semantics of the -s option
82    (or lack of same) when the specified field list includes (does
83    not include) the first field.  In both of those cases, the entire
84    first field must be read into this buffer to determine whether it
85    is followed by a delimiter or a newline before any of it may be
86    output.  Otherwise, cut_fields can do the job without using this
87    buffer.  */
88 static char *field_1_buffer;
89
90 /* The number of bytes allocated for FIELD_1_BUFFER.  */
91 static size_t field_1_bufsize;
92
93 /* The largest field or byte index used as an endpoint of a closed
94    or degenerate range specification;  this doesn't include the starting
95    index of right-open-ended ranges.  For example, with either range spec
96    '2-5,9-', '2-3,5,9-' this variable would be set to 5.  */
97 static size_t max_range_endpoint;
98
99 /* If nonzero, this is the index of the first field in a range that goes
100    to end of line. */
101 static size_t eol_range_start;
102
103 /* This is a bit vector.
104    In byte mode, which bytes to output.
105    In field mode, which DELIM-separated fields to output.
106    Both bytes and fields are numbered starting with 1,
107    so the zeroth bit of this array is unused.
108    A field or byte K has been selected if
109    (K <= MAX_RANGE_ENDPOINT and is_printable_field(K))
110     || (EOL_RANGE_START > 0 && K >= EOL_RANGE_START).  */
111 static unsigned char *printable_field;
112
113 enum operating_mode
114   {
115     undefined_mode,
116
117     /* Output characters that are in the given bytes. */
118     byte_mode,
119
120     /* Output the given delimeter-separated fields. */
121     field_mode
122   };
123
124 static enum operating_mode operating_mode;
125
126 /* If true do not output lines containing no delimeter characters.
127    Otherwise, all such lines are printed.  This option is valid only
128    with field mode.  */
129 static bool suppress_non_delimited;
130
131 /* If nonzero, print all bytes, characters, or fields _except_
132    those that were specified.  */
133 static bool complement;
134
135 /* The delimeter character for field mode. */
136 static unsigned char delim;
137
138 /* True if the --output-delimiter=STRING option was specified.  */
139 static bool output_delimiter_specified;
140
141 /* The length of output_delimiter_string.  */
142 static size_t output_delimiter_length;
143
144 /* The output field separator string.  Defaults to the 1-character
145    string consisting of the input delimiter.  */
146 static char *output_delimiter_string;
147
148 /* True if we have ever read standard input. */
149 static bool have_read_stdin;
150
151 #define HT_RANGE_START_INDEX_INITIAL_CAPACITY 31
152
153 /* The set of range-start indices.  For example, given a range-spec list like
154    '-b1,3-5,4-9,15-', the following indices will be recorded here: 1, 3, 15.
155    Note that although '4' looks like a range-start index, it is in the middle
156    of the '3-5' range, so it doesn't count.
157    This table is created/used IFF output_delimiter_specified is set.  */
158 static Hash_table *range_start_ht;
159
160 /* For long options that have no equivalent short option, use a
161    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
162 enum
163 {
164   OUTPUT_DELIMITER_OPTION = CHAR_MAX + 1,
165   COMPLEMENT_OPTION
166 };
167
168 static struct option const longopts[] =
169 {
170   {"bytes", required_argument, NULL, 'b'},
171   {"characters", required_argument, NULL, 'c'},
172   {"fields", required_argument, NULL, 'f'},
173   {"delimiter", required_argument, NULL, 'd'},
174   {"only-delimited", no_argument, NULL, 's'},
175   {"output-delimiter", required_argument, NULL, OUTPUT_DELIMITER_OPTION},
176   {"complement", no_argument, NULL, COMPLEMENT_OPTION},
177   {GETOPT_HELP_OPTION_DECL},
178   {GETOPT_VERSION_OPTION_DECL},
179   {NULL, 0, NULL, 0}
180 };
181
182 void
183 usage (int status)
184 {
185   if (status != EXIT_SUCCESS)
186     emit_try_help ();
187   else
188     {
189       printf (_("\
190 Usage: %s OPTION... [FILE]...\n\
191 "),
192               program_name);
193       fputs (_("\
194 Print selected parts of lines from each FILE to standard output.\n\
195 "), stdout);
196
197       emit_mandatory_arg_note ();
198
199       fputs (_("\
200   -b, --bytes=LIST        select only these bytes\n\
201   -c, --characters=LIST   select only these characters\n\
202   -d, --delimiter=DELIM   use DELIM instead of TAB for field delimiter\n\
203 "), stdout);
204       fputs (_("\
205   -f, --fields=LIST       select only these fields;  also print any line\n\
206                             that contains no delimiter character, unless\n\
207                             the -s option is specified\n\
208   -n                      (ignored)\n\
209 "), stdout);
210       fputs (_("\
211       --complement        complement the set of selected bytes, characters\n\
212                             or fields\n\
213 "), stdout);
214       fputs (_("\
215   -s, --only-delimited    do not print lines not containing delimiters\n\
216       --output-delimiter=STRING  use STRING as the output delimiter\n\
217                             the default is to use the input delimiter\n\
218 "), stdout);
219       fputs (HELP_OPTION_DESCRIPTION, stdout);
220       fputs (VERSION_OPTION_DESCRIPTION, stdout);
221       fputs (_("\
222 \n\
223 Use one, and only one of -b, -c or -f.  Each LIST is made up of one\n\
224 range, or many ranges separated by commas.  Selected input is written\n\
225 in the same order that it is read, and is written exactly once.\n\
226 "), stdout);
227       fputs (_("\
228 Each range is one of:\n\
229 \n\
230   N     N'th byte, character or field, counted from 1\n\
231   N-    from N'th byte, character or field, to end of line\n\
232   N-M   from N'th to M'th (included) byte, character or field\n\
233   -M    from first to M'th (included) byte, character or field\n\
234 \n\
235 With no FILE, or when FILE is -, read standard input.\n\
236 "), stdout);
237       emit_ancillary_info ();
238     }
239   exit (status);
240 }
241
242 static inline void
243 mark_range_start (size_t i)
244 {
245   /* Record the fact that 'i' is a range-start index.  */
246   void *ent_from_table = hash_insert (range_start_ht, (void*) i);
247   if (ent_from_table == NULL)
248     {
249       /* Insertion failed due to lack of memory.  */
250       xalloc_die ();
251     }
252   assert ((size_t) ent_from_table == i);
253 }
254
255 static inline void
256 mark_printable_field (size_t i)
257 {
258   size_t n = i / CHAR_BIT;
259   printable_field[n] |= (1 << (i % CHAR_BIT));
260 }
261
262 static inline bool
263 is_printable_field (size_t i)
264 {
265   size_t n = i / CHAR_BIT;
266   return (printable_field[n] >> (i % CHAR_BIT)) & 1;
267 }
268
269 static size_t
270 hash_int (const void *x, size_t tablesize)
271 {
272 #ifdef UINTPTR_MAX
273   uintptr_t y = (uintptr_t) x;
274 #else
275   size_t y = (size_t) x;
276 #endif
277   return y % tablesize;
278 }
279
280 static bool
281 hash_compare_ints (void const *x, void const *y)
282 {
283   return (x == y) ? true : false;
284 }
285
286 static bool
287 is_range_start_index (size_t i)
288 {
289   return hash_lookup (range_start_ht, (void *) i) ? true : false;
290 }
291
292 /* Return nonzero if the K'th field or byte is printable.
293    When returning nonzero, if RANGE_START is non-NULL,
294    set *RANGE_START to true if K is the beginning of a range, and to
295    false otherwise.  */
296
297 static bool
298 print_kth (size_t k, bool *range_start)
299 {
300   bool k_selected
301     = ((0 < eol_range_start && eol_range_start <= k)
302        || (k <= max_range_endpoint && is_printable_field (k)));
303
304   bool is_selected = k_selected ^ complement;
305   if (range_start && is_selected)
306     *range_start = is_range_start_index (k);
307
308   return is_selected;
309 }
310
311 /* Comparison function for qsort to order the list of
312    struct range_pairs.  */
313 static int
314 compare_ranges (const void *a, const void *b)
315 {
316   int a_start = ((const struct range_pair *) a)->lo;
317   int b_start = ((const struct range_pair *) b)->lo;
318   return a_start < b_start ? -1 : a_start > b_start;
319 }
320
321 /* Given the list of field or byte range specifications FIELDSTR, set
322    MAX_RANGE_ENDPOINT and allocate and initialize the PRINTABLE_FIELD
323    array.  If there is a right-open-ended range, set EOL_RANGE_START
324    to its starting index.  FIELDSTR should be composed of one or more
325    numbers or ranges of numbers, separated by blanks or commas.
326    Incomplete ranges may be given: '-m' means '1-m'; 'n-' means 'n'
327    through end of line.  Return true if FIELDSTR contains at least
328    one field specification, false otherwise.  */
329
330 /* FIXME-someday:  What if the user wants to cut out the 1,000,000-th
331    field of some huge input file?  This function shouldn't have to
332    allocate a table of a million bits just so we can test every
333    field < 10^6 with an array dereference.  Instead, consider using
334    an adaptive approach: if the range of selected fields is too large,
335    but only a few fields/byte-offsets are actually selected, use a
336    hash table.  If the range of selected fields is too large, and
337    too many are selected, then resort to using the range-pairs (the
338    'rp' array) directly.  */
339
340 static bool
341 set_fields (const char *fieldstr)
342 {
343   size_t initial = 1;           /* Value of first number in a range.  */
344   size_t value = 0;             /* If nonzero, a number being accumulated.  */
345   bool lhs_specified = false;
346   bool rhs_specified = false;
347   bool dash_found = false;      /* True if a '-' is found in this field.  */
348   bool field_found = false;     /* True if at least one field spec
349                                    has been processed.  */
350
351   struct range_pair *rp = NULL;
352   size_t n_rp = 0;
353   size_t n_rp_allocated = 0;
354   size_t i;
355   bool in_digits = false;
356
357   /* Collect and store in RP the range end points.
358      It also sets EOL_RANGE_START if appropriate.  */
359
360   while (true)
361     {
362       if (*fieldstr == '-')
363         {
364           in_digits = false;
365           /* Starting a range. */
366           if (dash_found)
367             FATAL_ERROR (_("invalid byte, character or field list"));
368           dash_found = true;
369           fieldstr++;
370
371           if (lhs_specified && !value)
372             FATAL_ERROR (_("fields and positions are numbered from 1"));
373
374           initial = (lhs_specified ? value : 1);
375           value = 0;
376         }
377       else if (*fieldstr == ','
378                || isblank (to_uchar (*fieldstr)) || *fieldstr == '\0')
379         {
380           in_digits = false;
381           /* Ending the string, or this field/byte sublist. */
382           if (dash_found)
383             {
384               dash_found = false;
385
386               if (!lhs_specified && !rhs_specified)
387                 FATAL_ERROR (_("invalid range with no endpoint: -"));
388
389               /* A range.  Possibilities: -n, m-n, n-.
390                  In any case, 'initial' contains the start of the range. */
391               if (!rhs_specified)
392                 {
393                   /* 'n-'.  From 'initial' to end of line.  If we've already
394                      seen an M- range, ignore subsequent N- unless N < M.  */
395                   if (eol_range_start == 0 || initial < eol_range_start)
396                     eol_range_start = initial;
397                   field_found = true;
398                 }
399               else
400                 {
401                   /* 'm-n' or '-n' (1-n). */
402                   if (value < initial)
403                     FATAL_ERROR (_("invalid decreasing range"));
404
405                   /* Is there already a range going to end of line? */
406                   if (eol_range_start != 0)
407                     {
408                       /* Yes.  Is the new sequence already contained
409                          in the old one?  If so, no processing is
410                          necessary. */
411                       if (initial < eol_range_start)
412                         {
413                           /* No, the new sequence starts before the
414                              old.  Does the old range going to end of line
415                              extend into the new range?  */
416                           if (eol_range_start <= value)
417                             {
418                               /* Yes.  Simply move the end of line marker. */
419                               eol_range_start = initial;
420                             }
421                           else
422                             {
423                               /* No.  A simple range, before and disjoint from
424                                  the range going to end of line.  Fill it. */
425                               ADD_RANGE_PAIR (rp, initial, value);
426                             }
427
428                           /* In any case, some fields were selected. */
429                           field_found = true;
430                         }
431                     }
432                   else
433                     {
434                       /* There is no range going to end of line. */
435                       ADD_RANGE_PAIR (rp, initial, value);
436                       field_found = true;
437                     }
438                   value = 0;
439                 }
440             }
441           else
442             {
443               /* A simple field number, not a range. */
444               ADD_RANGE_PAIR (rp, value, value);
445               value = 0;
446               field_found = true;
447             }
448
449           if (*fieldstr == '\0')
450             {
451               break;
452             }
453
454           fieldstr++;
455           lhs_specified = false;
456           rhs_specified = false;
457         }
458       else if (ISDIGIT (*fieldstr))
459         {
460           /* Record beginning of digit string, in case we have to
461              complain about it.  */
462           static char const *num_start;
463           if (!in_digits || !num_start)
464             num_start = fieldstr;
465           in_digits = true;
466
467           if (dash_found)
468             rhs_specified = 1;
469           else
470             lhs_specified = 1;
471
472           /* Detect overflow.  */
473           if (!DECIMAL_DIGIT_ACCUMULATE (value, *fieldstr - '0', size_t))
474             {
475               /* In case the user specified -c$(echo 2^64|bc),22,
476                  complain only about the first number.  */
477               /* Determine the length of the offending number.  */
478               size_t len = strspn (num_start, "0123456789");
479               char *bad_num = xstrndup (num_start, len);
480               if (operating_mode == byte_mode)
481                 error (0, 0,
482                        _("byte offset %s is too large"), quote (bad_num));
483               else
484                 error (0, 0,
485                        _("field number %s is too large"), quote (bad_num));
486               free (bad_num);
487               exit (EXIT_FAILURE);
488             }
489
490           fieldstr++;
491         }
492       else
493         FATAL_ERROR (_("invalid byte, character or field list"));
494     }
495
496   max_range_endpoint = 0;
497   for (i = 0; i < n_rp; i++)
498     {
499       if (rp[i].hi > max_range_endpoint)
500         max_range_endpoint = rp[i].hi;
501     }
502
503   /* Allocate an array large enough so that it may be indexed by
504      the field numbers corresponding to all finite ranges
505      (i.e. '2-6' or '-4', but not '5-') in FIELDSTR.  */
506
507   if (max_range_endpoint)
508     printable_field = xzalloc (max_range_endpoint / CHAR_BIT + 1);
509
510   qsort (rp, n_rp, sizeof (rp[0]), compare_ranges);
511
512   /* Set the array entries corresponding to integers in the ranges of RP.  */
513   for (i = 0; i < n_rp; i++)
514     {
515       /* Ignore any range that is subsumed by the to-EOL range.  */
516       if (eol_range_start && eol_range_start <= rp[i].lo)
517         continue;
518
519       /* Record the range-start indices, i.e., record each start
520          index that is not part of any other (lo..hi] range.  */
521       size_t rsi_candidate = complement ? rp[i].hi + 1 : rp[i].lo;
522       if (output_delimiter_specified
523           && !is_printable_field (rsi_candidate))
524         mark_range_start (rsi_candidate);
525
526       for (size_t j = rp[i].lo; j <= rp[i].hi; j++)
527         mark_printable_field (j);
528     }
529
530   if (output_delimiter_specified
531       && !complement
532       && eol_range_start
533       && max_range_endpoint && !is_printable_field (eol_range_start))
534     mark_range_start (eol_range_start);
535
536   free (rp);
537
538   return field_found;
539 }
540
541 /* Read from stream STREAM, printing to standard output any selected bytes.  */
542
543 static void
544 cut_bytes (FILE *stream)
545 {
546   size_t byte_idx;      /* Number of bytes in the line so far. */
547   /* Whether to begin printing delimiters between ranges for the current line.
548      Set after we've begun printing data corresponding to the first range.  */
549   bool print_delimiter;
550
551   byte_idx = 0;
552   print_delimiter = false;
553   while (1)
554     {
555       int c;            /* Each character from the file. */
556
557       c = getc (stream);
558
559       if (c == '\n')
560         {
561           putchar ('\n');
562           byte_idx = 0;
563           print_delimiter = false;
564         }
565       else if (c == EOF)
566         {
567           if (byte_idx > 0)
568             putchar ('\n');
569           break;
570         }
571       else
572         {
573           bool range_start;
574           bool *rs = output_delimiter_specified ? &range_start : NULL;
575           if (print_kth (++byte_idx, rs))
576             {
577               if (rs && *rs && print_delimiter)
578                 {
579                   fwrite (output_delimiter_string, sizeof (char),
580                           output_delimiter_length, stdout);
581                 }
582               print_delimiter = true;
583               putchar (c);
584             }
585         }
586     }
587 }
588
589 /* Read from stream STREAM, printing to standard output any selected fields.  */
590
591 static void
592 cut_fields (FILE *stream)
593 {
594   int c;
595   size_t field_idx = 1;
596   bool found_any_selected_field = false;
597   bool buffer_first_field;
598
599   c = getc (stream);
600   if (c == EOF)
601     return;
602
603   ungetc (c, stream);
604   c = 0;
605
606   /* To support the semantics of the -s flag, we may have to buffer
607      all of the first field to determine whether it is 'delimited.'
608      But that is unnecessary if all non-delimited lines must be printed
609      and the first field has been selected, or if non-delimited lines
610      must be suppressed and the first field has *not* been selected.
611      That is because a non-delimited line has exactly one field.  */
612   buffer_first_field = (suppress_non_delimited ^ !print_kth (1, NULL));
613
614   while (1)
615     {
616       if (field_idx == 1 && buffer_first_field)
617         {
618           ssize_t len;
619           size_t n_bytes;
620           bool got_line;
621
622           len = getndelim2 (&field_1_buffer, &field_1_bufsize, 0,
623                             GETNLINE_NO_LIMIT, delim, '\n', stream);
624           if (len < 0)
625             {
626               free (field_1_buffer);
627               field_1_buffer = NULL;
628               if (ferror (stream) || feof (stream))
629                 break;
630               xalloc_die ();
631             }
632
633           n_bytes = len;
634           assert (n_bytes != 0);
635
636           c = 0;
637           got_line = field_1_buffer[n_bytes - 1] == '\n';
638
639           /* If the first field extends to the end of line (it is not
640              delimited) and we are printing all non-delimited lines,
641              print this one.  */
642           if (to_uchar (field_1_buffer[n_bytes - 1]) != delim || got_line)
643             {
644               if (suppress_non_delimited && !(got_line && delim == '\n'))
645                 {
646                   /* Empty.  */
647                 }
648               else
649                 {
650                   fwrite (field_1_buffer, sizeof (char), n_bytes, stdout);
651                   /* Make sure the output line is newline terminated.  */
652                   if (! got_line)
653                     putchar ('\n');
654                   c = '\n';
655                 }
656               continue;
657             }
658           if (print_kth (1, NULL))
659             {
660               /* Print the field, but not the trailing delimiter.  */
661               fwrite (field_1_buffer, sizeof (char), n_bytes - 1, stdout);
662               found_any_selected_field = true;
663             }
664           ++field_idx;
665         }
666
667       int prev_c = c;
668
669       if (print_kth (field_idx, NULL))
670         {
671           if (found_any_selected_field)
672             {
673               fwrite (output_delimiter_string, sizeof (char),
674                       output_delimiter_length, stdout);
675             }
676           found_any_selected_field = true;
677
678           while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
679             {
680               putchar (c);
681               prev_c = c;
682             }
683         }
684       else
685         {
686           while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
687             {
688               prev_c = c;
689             }
690         }
691
692       if (c == '\n' || c == EOF)
693         {
694           if (found_any_selected_field
695               || !(suppress_non_delimited && field_idx == 1))
696             {
697               if (c == '\n' || prev_c != '\n')
698                 putchar ('\n');
699             }
700           if (c == EOF)
701             break;
702           field_idx = 1;
703           found_any_selected_field = false;
704         }
705       else if (c == delim)
706         field_idx++;
707     }
708 }
709
710 static void
711 cut_stream (FILE *stream)
712 {
713   if (operating_mode == byte_mode)
714     cut_bytes (stream);
715   else
716     cut_fields (stream);
717 }
718
719 /* Process file FILE to standard output.
720    Return true if successful.  */
721
722 static bool
723 cut_file (char const *file)
724 {
725   FILE *stream;
726
727   if (STREQ (file, "-"))
728     {
729       have_read_stdin = true;
730       stream = stdin;
731     }
732   else
733     {
734       stream = fopen (file, "r");
735       if (stream == NULL)
736         {
737           error (0, errno, "%s", file);
738           return false;
739         }
740     }
741
742   fadvise (stream, FADVISE_SEQUENTIAL);
743
744   cut_stream (stream);
745
746   if (ferror (stream))
747     {
748       error (0, errno, "%s", file);
749       return false;
750     }
751   if (STREQ (file, "-"))
752     clearerr (stream);          /* Also clear EOF. */
753   else if (fclose (stream) == EOF)
754     {
755       error (0, errno, "%s", file);
756       return false;
757     }
758   return true;
759 }
760
761 int
762 main (int argc, char **argv)
763 {
764   int optc;
765   bool ok;
766   bool delim_specified = false;
767   char *spec_list_string IF_LINT ( = NULL);
768
769   initialize_main (&argc, &argv);
770   set_program_name (argv[0]);
771   setlocale (LC_ALL, "");
772   bindtextdomain (PACKAGE, LOCALEDIR);
773   textdomain (PACKAGE);
774
775   atexit (close_stdout);
776
777   operating_mode = undefined_mode;
778
779   /* By default, all non-delimited lines are printed.  */
780   suppress_non_delimited = false;
781
782   delim = '\0';
783   have_read_stdin = false;
784
785   while ((optc = getopt_long (argc, argv, "b:c:d:f:ns", longopts, NULL)) != -1)
786     {
787       switch (optc)
788         {
789         case 'b':
790         case 'c':
791           /* Build the byte list. */
792           if (operating_mode != undefined_mode)
793             FATAL_ERROR (_("only one type of list may be specified"));
794           operating_mode = byte_mode;
795           spec_list_string = optarg;
796           break;
797
798         case 'f':
799           /* Build the field list. */
800           if (operating_mode != undefined_mode)
801             FATAL_ERROR (_("only one type of list may be specified"));
802           operating_mode = field_mode;
803           spec_list_string = optarg;
804           break;
805
806         case 'd':
807           /* New delimiter. */
808           /* Interpret -d '' to mean 'use the NUL byte as the delimiter.'  */
809           if (optarg[0] != '\0' && optarg[1] != '\0')
810             FATAL_ERROR (_("the delimiter must be a single character"));
811           delim = optarg[0];
812           delim_specified = true;
813           break;
814
815         case OUTPUT_DELIMITER_OPTION:
816           output_delimiter_specified = true;
817           /* Interpret --output-delimiter='' to mean
818              'use the NUL byte as the delimiter.'  */
819           output_delimiter_length = (optarg[0] == '\0'
820                                      ? 1 : strlen (optarg));
821           output_delimiter_string = xstrdup (optarg);
822           break;
823
824         case 'n':
825           break;
826
827         case 's':
828           suppress_non_delimited = true;
829           break;
830
831         case COMPLEMENT_OPTION:
832           complement = true;
833           break;
834
835         case_GETOPT_HELP_CHAR;
836
837         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
838
839         default:
840           usage (EXIT_FAILURE);
841         }
842     }
843
844   if (operating_mode == undefined_mode)
845     FATAL_ERROR (_("you must specify a list of bytes, characters, or fields"));
846
847   if (delim_specified && operating_mode != field_mode)
848     FATAL_ERROR (_("an input delimiter may be specified only\
849  when operating on fields"));
850
851   if (suppress_non_delimited && operating_mode != field_mode)
852     FATAL_ERROR (_("suppressing non-delimited lines makes sense\n\
853 \tonly when operating on fields"));
854
855   if (output_delimiter_specified)
856     {
857       range_start_ht = hash_initialize (HT_RANGE_START_INDEX_INITIAL_CAPACITY,
858                                         NULL, hash_int,
859                                         hash_compare_ints, NULL);
860       if (range_start_ht == NULL)
861         xalloc_die ();
862
863     }
864
865   if (! set_fields (spec_list_string))
866     {
867       if (operating_mode == field_mode)
868         FATAL_ERROR (_("missing list of fields"));
869       else
870         FATAL_ERROR (_("missing list of positions"));
871     }
872
873   if (!delim_specified)
874     delim = '\t';
875
876   if (output_delimiter_string == NULL)
877     {
878       static char dummy[2];
879       dummy[0] = delim;
880       dummy[1] = '\0';
881       output_delimiter_string = dummy;
882       output_delimiter_length = 1;
883     }
884
885   if (optind == argc)
886     ok = cut_file ("-");
887   else
888     for (ok = true; optind < argc; optind++)
889       ok &= cut_file (argv[optind]);
890
891   if (range_start_ht)
892     hash_free (range_start_ht);
893
894   if (have_read_stdin && fclose (stdin) == EOF)
895     {
896       error (0, errno, "-");
897       ok = false;
898     }
899
900   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
901 }