maint: update all copyright year number ranges
[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 \n\
196 "), stdout);
197       fputs (_("\
198 Mandatory arguments to long options are mandatory for short options too.\n\
199 "), stdout);
200       fputs (_("\
201   -b, --bytes=LIST        select only these bytes\n\
202   -c, --characters=LIST   select only these characters\n\
203   -d, --delimiter=DELIM   use DELIM instead of TAB for field delimiter\n\
204 "), stdout);
205       fputs (_("\
206   -f, --fields=LIST       select only these fields;  also print any line\n\
207                             that contains no delimiter character, unless\n\
208                             the -s option is specified\n\
209   -n                      (ignored)\n\
210 "), stdout);
211       fputs (_("\
212       --complement        complement the set of selected bytes, characters\n\
213                             or fields\n\
214 "), stdout);
215       fputs (_("\
216   -s, --only-delimited    do not print lines not containing delimiters\n\
217       --output-delimiter=STRING  use STRING as the output delimiter\n\
218                             the default is to use the input delimiter\n\
219 "), stdout);
220       fputs (HELP_OPTION_DESCRIPTION, stdout);
221       fputs (VERSION_OPTION_DESCRIPTION, stdout);
222       fputs (_("\
223 \n\
224 Use one, and only one of -b, -c or -f.  Each LIST is made up of one\n\
225 range, or many ranges separated by commas.  Selected input is written\n\
226 in the same order that it is read, and is written exactly once.\n\
227 "), stdout);
228       fputs (_("\
229 Each range is one of:\n\
230 \n\
231   N     N'th byte, character or field, counted from 1\n\
232   N-    from N'th byte, character or field, to end of line\n\
233   N-M   from N'th to M'th (included) byte, character or field\n\
234   -M    from first to M'th (included) byte, character or field\n\
235 \n\
236 With no FILE, or when FILE is -, read standard input.\n\
237 "), stdout);
238       emit_ancillary_info ();
239     }
240   exit (status);
241 }
242
243 static inline void
244 mark_range_start (size_t i)
245 {
246   /* Record the fact that 'i' is a range-start index.  */
247   void *ent_from_table = hash_insert (range_start_ht, (void*) i);
248   if (ent_from_table == NULL)
249     {
250       /* Insertion failed due to lack of memory.  */
251       xalloc_die ();
252     }
253   assert ((size_t) ent_from_table == i);
254 }
255
256 static inline void
257 mark_printable_field (size_t i)
258 {
259   size_t n = i / CHAR_BIT;
260   printable_field[n] |= (1 << (i % CHAR_BIT));
261 }
262
263 static inline bool
264 is_printable_field (size_t i)
265 {
266   size_t n = i / CHAR_BIT;
267   return (printable_field[n] >> (i % CHAR_BIT)) & 1;
268 }
269
270 static size_t
271 hash_int (const void *x, size_t tablesize)
272 {
273 #ifdef UINTPTR_MAX
274   uintptr_t y = (uintptr_t) x;
275 #else
276   size_t y = (size_t) x;
277 #endif
278   return y % tablesize;
279 }
280
281 static bool
282 hash_compare_ints (void const *x, void const *y)
283 {
284   return (x == y) ? true : false;
285 }
286
287 static bool
288 is_range_start_index (size_t i)
289 {
290   return hash_lookup (range_start_ht, (void *) i) ? true : false;
291 }
292
293 /* Return nonzero if the K'th field or byte is printable.
294    When returning nonzero, if RANGE_START is non-NULL,
295    set *RANGE_START to true if K is the beginning of a range, and to
296    false otherwise.  */
297
298 static bool
299 print_kth (size_t k, bool *range_start)
300 {
301   bool k_selected
302     = ((0 < eol_range_start && eol_range_start <= k)
303        || (k <= max_range_endpoint && is_printable_field (k)));
304
305   bool is_selected = k_selected ^ complement;
306   if (range_start && is_selected)
307     *range_start = is_range_start_index (k);
308
309   return is_selected;
310 }
311
312 /* Comparison function for qsort to order the list of
313    struct range_pairs.  */
314 static int
315 compare_ranges (const void *a, const void *b)
316 {
317   int a_start = ((const struct range_pair *) a)->lo;
318   int b_start = ((const struct range_pair *) b)->lo;
319   return a_start < b_start ? -1 : a_start > b_start;
320 }
321
322 /* Given the list of field or byte range specifications FIELDSTR, set
323    MAX_RANGE_ENDPOINT and allocate and initialize the PRINTABLE_FIELD
324    array.  If there is a right-open-ended range, set EOL_RANGE_START
325    to its starting index.  FIELDSTR should be composed of one or more
326    numbers or ranges of numbers, separated by blanks or commas.
327    Incomplete ranges may be given: '-m' means '1-m'; 'n-' means 'n'
328    through end of line.  Return true if FIELDSTR contains at least
329    one field specification, false otherwise.  */
330
331 /* FIXME-someday:  What if the user wants to cut out the 1,000,000-th
332    field of some huge input file?  This function shouldn't have to
333    allocate a table of a million bits just so we can test every
334    field < 10^6 with an array dereference.  Instead, consider using
335    an adaptive approach: if the range of selected fields is too large,
336    but only a few fields/byte-offsets are actually selected, use a
337    hash table.  If the range of selected fields is too large, and
338    too many are selected, then resort to using the range-pairs (the
339    'rp' array) directly.  */
340
341 static bool
342 set_fields (const char *fieldstr)
343 {
344   size_t initial = 1;           /* Value of first number in a range.  */
345   size_t value = 0;             /* If nonzero, a number being accumulated.  */
346   bool lhs_specified = false;
347   bool rhs_specified = false;
348   bool dash_found = false;      /* True if a '-' is found in this field.  */
349   bool field_found = false;     /* True if at least one field spec
350                                    has been processed.  */
351
352   struct range_pair *rp = NULL;
353   size_t n_rp = 0;
354   size_t n_rp_allocated = 0;
355   size_t i;
356   bool in_digits = false;
357
358   /* Collect and store in RP the range end points.
359      It also sets EOL_RANGE_START if appropriate.  */
360
361   while (true)
362     {
363       if (*fieldstr == '-')
364         {
365           in_digits = false;
366           /* Starting a range. */
367           if (dash_found)
368             FATAL_ERROR (_("invalid byte, character or field list"));
369           dash_found = true;
370           fieldstr++;
371
372           if (lhs_specified && !value)
373             FATAL_ERROR (_("fields and positions are numbered from 1"));
374
375           initial = (lhs_specified ? value : 1);
376           value = 0;
377         }
378       else if (*fieldstr == ','
379                || isblank (to_uchar (*fieldstr)) || *fieldstr == '\0')
380         {
381           in_digits = false;
382           /* Ending the string, or this field/byte sublist. */
383           if (dash_found)
384             {
385               dash_found = false;
386
387               if (!lhs_specified && !rhs_specified)
388                 FATAL_ERROR (_("invalid range with no endpoint: -"));
389
390               /* A range.  Possibilities: -n, m-n, n-.
391                  In any case, 'initial' contains the start of the range. */
392               if (!rhs_specified)
393                 {
394                   /* 'n-'.  From 'initial' to end of line.  If we've already
395                      seen an M- range, ignore subsequent N- unless N < M.  */
396                   if (eol_range_start == 0 || initial < eol_range_start)
397                     eol_range_start = initial;
398                   field_found = true;
399                 }
400               else
401                 {
402                   /* 'm-n' or '-n' (1-n). */
403                   if (value < initial)
404                     FATAL_ERROR (_("invalid decreasing range"));
405
406                   /* Is there already a range going to end of line? */
407                   if (eol_range_start != 0)
408                     {
409                       /* Yes.  Is the new sequence already contained
410                          in the old one?  If so, no processing is
411                          necessary. */
412                       if (initial < eol_range_start)
413                         {
414                           /* No, the new sequence starts before the
415                              old.  Does the old range going to end of line
416                              extend into the new range?  */
417                           if (eol_range_start <= value)
418                             {
419                               /* Yes.  Simply move the end of line marker. */
420                               eol_range_start = initial;
421                             }
422                           else
423                             {
424                               /* No.  A simple range, before and disjoint from
425                                  the range going to end of line.  Fill it. */
426                               ADD_RANGE_PAIR (rp, initial, value);
427                             }
428
429                           /* In any case, some fields were selected. */
430                           field_found = true;
431                         }
432                     }
433                   else
434                     {
435                       /* There is no range going to end of line. */
436                       ADD_RANGE_PAIR (rp, initial, value);
437                       field_found = true;
438                     }
439                   value = 0;
440                 }
441             }
442           else
443             {
444               /* A simple field number, not a range. */
445               ADD_RANGE_PAIR (rp, value, value);
446               value = 0;
447               field_found = true;
448             }
449
450           if (*fieldstr == '\0')
451             {
452               break;
453             }
454
455           fieldstr++;
456           lhs_specified = false;
457           rhs_specified = false;
458         }
459       else if (ISDIGIT (*fieldstr))
460         {
461           /* Record beginning of digit string, in case we have to
462              complain about it.  */
463           static char const *num_start;
464           if (!in_digits || !num_start)
465             num_start = fieldstr;
466           in_digits = true;
467
468           if (dash_found)
469             rhs_specified = 1;
470           else
471             lhs_specified = 1;
472
473           /* Detect overflow.  */
474           if (!DECIMAL_DIGIT_ACCUMULATE (value, *fieldstr - '0', size_t))
475             {
476               /* In case the user specified -c$(echo 2^64|bc),22,
477                  complain only about the first number.  */
478               /* Determine the length of the offending number.  */
479               size_t len = strspn (num_start, "0123456789");
480               char *bad_num = xstrndup (num_start, len);
481               if (operating_mode == byte_mode)
482                 error (0, 0,
483                        _("byte offset %s is too large"), quote (bad_num));
484               else
485                 error (0, 0,
486                        _("field number %s is too large"), quote (bad_num));
487               free (bad_num);
488               exit (EXIT_FAILURE);
489             }
490
491           fieldstr++;
492         }
493       else
494         FATAL_ERROR (_("invalid byte, character or field list"));
495     }
496
497   max_range_endpoint = 0;
498   for (i = 0; i < n_rp; i++)
499     {
500       if (rp[i].hi > max_range_endpoint)
501         max_range_endpoint = rp[i].hi;
502     }
503
504   /* Allocate an array large enough so that it may be indexed by
505      the field numbers corresponding to all finite ranges
506      (i.e. '2-6' or '-4', but not '5-') in FIELDSTR.  */
507
508   if (max_range_endpoint)
509     printable_field = xzalloc (max_range_endpoint / CHAR_BIT + 1);
510
511   qsort (rp, n_rp, sizeof (rp[0]), compare_ranges);
512
513   /* Set the array entries corresponding to integers in the ranges of RP.  */
514   for (i = 0; i < n_rp; i++)
515     {
516       /* Ignore any range that is subsumed by the to-EOL range.  */
517       if (eol_range_start && eol_range_start <= rp[i].lo)
518         continue;
519
520       /* Record the range-start indices, i.e., record each start
521          index that is not part of any other (lo..hi] range.  */
522       size_t rsi_candidate = complement ? rp[i].hi + 1 : rp[i].lo;
523       if (output_delimiter_specified
524           && !is_printable_field (rsi_candidate))
525         mark_range_start (rsi_candidate);
526
527       for (size_t j = rp[i].lo; j <= rp[i].hi; j++)
528         mark_printable_field (j);
529     }
530
531   if (output_delimiter_specified
532       && !complement
533       && eol_range_start
534       && max_range_endpoint && !is_printable_field (eol_range_start))
535     mark_range_start (eol_range_start);
536
537   free (rp);
538
539   return field_found;
540 }
541
542 /* Read from stream STREAM, printing to standard output any selected bytes.  */
543
544 static void
545 cut_bytes (FILE *stream)
546 {
547   size_t byte_idx;      /* Number of bytes in the line so far. */
548   /* Whether to begin printing delimiters between ranges for the current line.
549      Set after we've begun printing data corresponding to the first range.  */
550   bool print_delimiter;
551
552   byte_idx = 0;
553   print_delimiter = false;
554   while (1)
555     {
556       int c;            /* Each character from the file. */
557
558       c = getc (stream);
559
560       if (c == '\n')
561         {
562           putchar ('\n');
563           byte_idx = 0;
564           print_delimiter = false;
565         }
566       else if (c == EOF)
567         {
568           if (byte_idx > 0)
569             putchar ('\n');
570           break;
571         }
572       else
573         {
574           bool range_start;
575           bool *rs = output_delimiter_specified ? &range_start : NULL;
576           if (print_kth (++byte_idx, rs))
577             {
578               if (rs && *rs && print_delimiter)
579                 {
580                   fwrite (output_delimiter_string, sizeof (char),
581                           output_delimiter_length, stdout);
582                 }
583               print_delimiter = true;
584               putchar (c);
585             }
586         }
587     }
588 }
589
590 /* Read from stream STREAM, printing to standard output any selected fields.  */
591
592 static void
593 cut_fields (FILE *stream)
594 {
595   int c;
596   size_t field_idx = 1;
597   bool found_any_selected_field = false;
598   bool buffer_first_field;
599
600   c = getc (stream);
601   if (c == EOF)
602     return;
603
604   ungetc (c, stream);
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
621           len = getndelim2 (&field_1_buffer, &field_1_bufsize, 0,
622                             GETNLINE_NO_LIMIT, delim, '\n', stream);
623           if (len < 0)
624             {
625               free (field_1_buffer);
626               field_1_buffer = NULL;
627               if (ferror (stream) || feof (stream))
628                 break;
629               xalloc_die ();
630             }
631
632           n_bytes = len;
633           assert (n_bytes != 0);
634
635           /* If the first field extends to the end of line (it is not
636              delimited) and we are printing all non-delimited lines,
637              print this one.  */
638           if (to_uchar (field_1_buffer[n_bytes - 1]) != delim)
639             {
640               if (suppress_non_delimited)
641                 {
642                   /* Empty.  */
643                 }
644               else
645                 {
646                   fwrite (field_1_buffer, sizeof (char), n_bytes, stdout);
647                   /* Make sure the output line is newline terminated.  */
648                   if (field_1_buffer[n_bytes - 1] != '\n')
649                     putchar ('\n');
650                 }
651               continue;
652             }
653           if (print_kth (1, NULL))
654             {
655               /* Print the field, but not the trailing delimiter.  */
656               fwrite (field_1_buffer, sizeof (char), n_bytes - 1, stdout);
657               found_any_selected_field = true;
658             }
659           ++field_idx;
660         }
661
662       if (c != EOF)
663         {
664           if (print_kth (field_idx, NULL))
665             {
666               if (found_any_selected_field)
667                 {
668                   fwrite (output_delimiter_string, sizeof (char),
669                           output_delimiter_length, stdout);
670                 }
671               found_any_selected_field = true;
672
673               while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
674                 {
675                   putchar (c);
676                 }
677             }
678           else
679             {
680               while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
681                 {
682                   /* Empty.  */
683                 }
684             }
685         }
686
687       if (c == '\n')
688         {
689           c = getc (stream);
690           if (c != EOF)
691             {
692               ungetc (c, stream);
693               c = '\n';
694             }
695         }
696
697       if (c == delim)
698         ++field_idx;
699       else if (c == '\n' || c == EOF)
700         {
701           if (found_any_selected_field
702               || !(suppress_non_delimited && field_idx == 1))
703             putchar ('\n');
704           if (c == EOF)
705             break;
706           field_idx = 1;
707           found_any_selected_field = false;
708         }
709     }
710 }
711
712 static void
713 cut_stream (FILE *stream)
714 {
715   if (operating_mode == byte_mode)
716     cut_bytes (stream);
717   else
718     cut_fields (stream);
719 }
720
721 /* Process file FILE to standard output.
722    Return true if successful.  */
723
724 static bool
725 cut_file (char const *file)
726 {
727   FILE *stream;
728
729   if (STREQ (file, "-"))
730     {
731       have_read_stdin = true;
732       stream = stdin;
733     }
734   else
735     {
736       stream = fopen (file, "r");
737       if (stream == NULL)
738         {
739           error (0, errno, "%s", file);
740           return false;
741         }
742     }
743
744   fadvise (stream, FADVISE_SEQUENTIAL);
745
746   cut_stream (stream);
747
748   if (ferror (stream))
749     {
750       error (0, errno, "%s", file);
751       return false;
752     }
753   if (STREQ (file, "-"))
754     clearerr (stream);          /* Also clear EOF. */
755   else if (fclose (stream) == EOF)
756     {
757       error (0, errno, "%s", file);
758       return false;
759     }
760   return true;
761 }
762
763 int
764 main (int argc, char **argv)
765 {
766   int optc;
767   bool ok;
768   bool delim_specified = false;
769   char *spec_list_string IF_LINT ( = NULL);
770
771   initialize_main (&argc, &argv);
772   set_program_name (argv[0]);
773   setlocale (LC_ALL, "");
774   bindtextdomain (PACKAGE, LOCALEDIR);
775   textdomain (PACKAGE);
776
777   atexit (close_stdout);
778
779   operating_mode = undefined_mode;
780
781   /* By default, all non-delimited lines are printed.  */
782   suppress_non_delimited = false;
783
784   delim = '\0';
785   have_read_stdin = false;
786
787   while ((optc = getopt_long (argc, argv, "b:c:d:f:ns", longopts, NULL)) != -1)
788     {
789       switch (optc)
790         {
791         case 'b':
792         case 'c':
793           /* Build the byte list. */
794           if (operating_mode != undefined_mode)
795             FATAL_ERROR (_("only one type of list may be specified"));
796           operating_mode = byte_mode;
797           spec_list_string = optarg;
798           break;
799
800         case 'f':
801           /* Build the field list. */
802           if (operating_mode != undefined_mode)
803             FATAL_ERROR (_("only one type of list may be specified"));
804           operating_mode = field_mode;
805           spec_list_string = optarg;
806           break;
807
808         case 'd':
809           /* New delimiter. */
810           /* Interpret -d '' to mean 'use the NUL byte as the delimiter.'  */
811           if (optarg[0] != '\0' && optarg[1] != '\0')
812             FATAL_ERROR (_("the delimiter must be a single character"));
813           delim = optarg[0];
814           delim_specified = true;
815           break;
816
817         case OUTPUT_DELIMITER_OPTION:
818           output_delimiter_specified = true;
819           /* Interpret --output-delimiter='' to mean
820              'use the NUL byte as the delimiter.'  */
821           output_delimiter_length = (optarg[0] == '\0'
822                                      ? 1 : strlen (optarg));
823           output_delimiter_string = xstrdup (optarg);
824           break;
825
826         case 'n':
827           break;
828
829         case 's':
830           suppress_non_delimited = true;
831           break;
832
833         case COMPLEMENT_OPTION:
834           complement = true;
835           break;
836
837         case_GETOPT_HELP_CHAR;
838
839         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
840
841         default:
842           usage (EXIT_FAILURE);
843         }
844     }
845
846   if (operating_mode == undefined_mode)
847     FATAL_ERROR (_("you must specify a list of bytes, characters, or fields"));
848
849   if (delim_specified && operating_mode != field_mode)
850     FATAL_ERROR (_("an input delimiter may be specified only\
851  when operating on fields"));
852
853   if (suppress_non_delimited && operating_mode != field_mode)
854     FATAL_ERROR (_("suppressing non-delimited lines makes sense\n\
855 \tonly when operating on fields"));
856
857   if (output_delimiter_specified)
858     {
859       range_start_ht = hash_initialize (HT_RANGE_START_INDEX_INITIAL_CAPACITY,
860                                         NULL, hash_int,
861                                         hash_compare_ints, NULL);
862       if (range_start_ht == NULL)
863         xalloc_die ();
864
865     }
866
867   if (! set_fields (spec_list_string))
868     {
869       if (operating_mode == field_mode)
870         FATAL_ERROR (_("missing list of fields"));
871       else
872         FATAL_ERROR (_("missing list of positions"));
873     }
874
875   if (!delim_specified)
876     delim = '\t';
877
878   if (output_delimiter_string == NULL)
879     {
880       static char dummy[2];
881       dummy[0] = delim;
882       dummy[1] = '\0';
883       output_delimiter_string = dummy;
884       output_delimiter_length = 1;
885     }
886
887   if (optind == argc)
888     ok = cut_file ("-");
889   else
890     for (ok = true; optind < argc; optind++)
891       ok &= cut_file (argv[optind]);
892
893   if (range_start_ht)
894     hash_free (range_start_ht);
895
896   if (have_read_stdin && fclose (stdin) == EOF)
897     {
898       error (0, errno, "-");
899       ok = false;
900     }
901
902   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
903 }