(usage): Say that
[platform/upstream/coreutils.git] / src / cut.c
1 /* cut - remove parts of lines of files
2    Copyright (C) 1984, 1997, 1998, 1999, 2000, 2001 by David M. Ihnat
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
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 #include "getstr.h"
33 #include "closeout.h"
34 #include "error.h"
35
36 /* The official name of this program (e.g., no `g' prefix).  */
37 #define PROGRAM_NAME "cut"
38
39 #define AUTHORS N_ ("David Ihnat, David MacKenzie, and Jim Meyering")
40
41 #define FATAL_ERROR(Message)                                            \
42   do                                                                    \
43     {                                                                   \
44       error (0, 0, (Message));                                          \
45       usage (2);                                                        \
46     }                                                                   \
47   while (0)
48
49 /* Append LOW, HIGH to the list RP of range pairs, allocating additional
50    space if necessary.  Update local variable N_RP.  When allocating,
51    update global variable N_RP_ALLOCATED.  */
52
53 #define ADD_RANGE_PAIR(rp, low, high)                                   \
54   do                                                                    \
55     {                                                                   \
56       if (n_rp >= n_rp_allocated)                                       \
57         {                                                               \
58           n_rp_allocated *= 2;                                          \
59           (rp) = (struct range_pair *) xrealloc ((char *) (rp),         \
60                                    n_rp_allocated * sizeof (*(rp)));    \
61         }                                                               \
62       rp[n_rp].lo = (low);                                              \
63       rp[n_rp].hi = (high);                                             \
64       ++n_rp;                                                           \
65     }                                                                   \
66   while (0)
67
68 struct range_pair
69   {
70     unsigned int lo;
71     unsigned int hi;
72   };
73
74 /* This buffer is used to support the semantics of the -s option
75    (or lack of same) when the specified field list includes (does
76    not include) the first field.  In both of those cases, the entire
77    first field must be read into this buffer to determine whether it
78    is followed by a delimiter or a newline before any of it may be
79    output.  Otherwise, cut_fields can do the job without using this
80    buffer.  */
81 static char *field_1_buffer;
82
83 /* The number of bytes allocated for FIELD_1_BUFFER.  */
84 static size_t field_1_bufsize;
85
86 /* The largest field or byte index used as an endpoint of a closed
87    or degenerate range specification;  this doesn't include the starting
88    index of right-open-ended ranges.  For example, with either range spec
89    `2-5,9-', `2-3,5,9-' this variable would be set to 5.  */
90 static unsigned int max_range_endpoint;
91
92 /* If nonzero, this is the index of the first field in a range that goes
93    to end of line. */
94 static unsigned int eol_range_start;
95
96 /* In byte mode, which bytes to output.
97    In field mode, which DELIM-separated fields to output.
98    Both bytes and fields are numbered starting with 1,
99    so the zeroth element of this array is unused.
100    A field or byte K has been selected if
101    (K <= MAX_RANGE_ENDPOINT and PRINTABLE_FIELD[K])
102     || (EOL_RANGE_START > 0 && K >= EOL_RANGE_START).  */
103 static int *printable_field;
104
105 enum operating_mode
106   {
107     undefined_mode,
108
109     /* Output characters that are in the given bytes. */
110     byte_mode,
111
112     /* Output the given delimeter-separated fields. */
113     field_mode
114   };
115
116 /* The name this program was run with. */
117 char *program_name;
118
119 static enum operating_mode operating_mode;
120
121 /* If nonzero do not output lines containing no delimeter characters.
122    Otherwise, all such lines are printed.  This option is valid only
123    with field mode.  */
124 static int suppress_non_delimited;
125
126 /* The delimeter character for field mode. */
127 static int delim;
128
129 /* The length of output_delimiter_string.  */
130 static size_t output_delimiter_length;
131
132 /* The output field separator string.  Defaults to the 1-character
133    string consisting of the input delimiter.  */
134 static char *output_delimiter_string;
135
136 /* Nonzero if we have ever read standard input. */
137 static int have_read_stdin;
138
139 /* For long options that have no equivalent short option, use a
140    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
141 enum
142 {
143   OUTPUT_DELIMITER_OPTION = CHAR_MAX + 1
144 };
145
146 static struct option const longopts[] =
147 {
148   {"bytes", required_argument, 0, 'b'},
149   {"characters", required_argument, 0, 'c'},
150   {"fields", required_argument, 0, 'f'},
151   {"delimiter", required_argument, 0, 'd'},
152   {"only-delimited", no_argument, 0, 's'},
153   {"output-delimiter", required_argument, 0, OUTPUT_DELIMITER_OPTION},
154   {GETOPT_HELP_OPTION_DECL},
155   {GETOPT_VERSION_OPTION_DECL},
156   {0, 0, 0, 0}
157 };
158
159 void
160 usage (int status)
161 {
162   if (status != 0)
163     fprintf (stderr, _("Try `%s --help' for more information.\n"),
164              program_name);
165   else
166     {
167       printf (_("\
168 Usage: %s [OPTION]... [FILE]...\n\
169 "),
170               program_name);
171       printf (_("\
172 Print selected parts of lines from each FILE to standard output.\n\
173 \n\
174 Mandatory arguments to long options are mandatory for short options too.\n\
175   -b, --bytes=LIST        output only these bytes\n\
176   -c, --characters=LIST   output only these characters\n\
177   -d, --delimiter=DELIM   use DELIM instead of TAB for field delimiter\n\
178   -f, --fields=LIST       output only these fields;  also print any line\n\
179                             that contains no delimiter character, unless\n\
180                             the -s option is specified\n\
181   -n                      (ignored)\n\
182   -s, --only-delimited    do not print lines not containing delimiters\n\
183       --output-delimiter=STRING  use STRING as the output delimiter\n\
184                             the default is to use the input delimiter\n\
185       --help              display this help and exit\n\
186       --version           output version information and exit\n\
187 \n\
188 Use one, and only one of -b, -c or -f.  Each LIST is made up of one\n\
189 range, or many ranges separated by commas.  Each range is one of:\n\
190 \n\
191   N     N'th byte, character or field, counted from 1\n\
192   N-    from N'th byte, character or field, to end of line\n\
193   N-M   from N'th to M'th (included) byte, character or field\n\
194   -M    from first to M'th (included) byte, character or field\n\
195 \n\
196 With no FILE, or when FILE is -, read standard input.\n\
197 "));
198       puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
199     }
200   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
201 }
202
203 static int
204 print_kth (unsigned int k)
205 {
206   return ((0 < eol_range_start && eol_range_start <= k)
207           || (k <= max_range_endpoint && printable_field[k]));
208 }
209
210 /* Given the list of field or byte range specifications FIELDSTR, set
211    MAX_RANGE_ENDPOINT and allocate and initialize the PRINTABLE_FIELD
212    array.  If there is a right-open-ended range, set EOL_RANGE_START
213    to its starting index.  FIELDSTR should be composed of one or more
214    numbers or ranges of numbers, separated by blanks or commas.
215    Incomplete ranges may be given: `-m' means `1-m'; `n-' means `n'
216    through end of line.  Return nonzero if FIELDSTR contains at least
217    one field specification, zero otherwise.  */
218
219 /* FIXME-someday:  What if the user wants to cut out the 1,000,000-th field
220    of some huge input file?  This function shouldn't have to alloate a table
221    of a million ints just so we can test every field < 10^6 with an array
222    dereference.  Instead, consider using a dynamic hash table.  It would be
223    simpler and nearly as good a solution to use a 32K x 4-byte table with
224    one bit per field index instead of a whole `int' per index.  */
225
226 static int
227 set_fields (const char *fieldstr)
228 {
229   unsigned int initial = 1;     /* Value of first number in a range.  */
230   unsigned int value = 0;       /* If nonzero, a number being accumulated.  */
231   int dash_found = 0;           /* Nonzero if a '-' is found in this field.  */
232   int field_found = 0;          /* Non-zero if at least one field spec
233                                    has been processed.  */
234
235   struct range_pair *rp;
236   unsigned int n_rp;
237   unsigned int n_rp_allocated;
238   unsigned int i;
239
240   n_rp = 0;
241   n_rp_allocated = 16;
242   rp = (struct range_pair *) xmalloc (n_rp_allocated * sizeof (*rp));
243
244   /* Collect and store in RP the range end points.
245      It also sets EOL_RANGE_START if appropriate.  */
246
247   for (;;)
248     {
249       if (*fieldstr == '-')
250         {
251           /* Starting a range. */
252           if (dash_found)
253             FATAL_ERROR (_("invalid byte or field list"));
254           dash_found++;
255           fieldstr++;
256
257           if (value)
258             {
259               initial = value;
260               value = 0;
261             }
262           else
263             initial = 1;
264         }
265       else if (*fieldstr == ',' || ISBLANK (*fieldstr) || *fieldstr == '\0')
266         {
267           /* Ending the string, or this field/byte sublist. */
268           if (dash_found)
269             {
270               dash_found = 0;
271
272               /* A range.  Possibilites: -n, m-n, n-.
273                  In any case, `initial' contains the start of the range. */
274               if (value == 0)
275                 {
276                   /* `n-'.  From `initial' to end of line. */
277                   eol_range_start = initial;
278                   field_found = 1;
279                 }
280               else
281                 {
282                   /* `m-n' or `-n' (1-n). */
283                   if (value < initial)
284                     FATAL_ERROR (_("invalid byte or field list"));
285
286                   /* Is there already a range going to end of line? */
287                   if (eol_range_start != 0)
288                     {
289                       /* Yes.  Is the new sequence already contained
290                          in the old one?  If so, no processing is
291                          necessary. */
292                       if (initial < eol_range_start)
293                         {
294                           /* No, the new sequence starts before the
295                              old.  Does the old range going to end of line
296                              extend into the new range?  */
297                           if (value + 1 >= eol_range_start)
298                             {
299                               /* Yes.  Simply move the end of line marker. */
300                               eol_range_start = initial;
301                             }
302                           else
303                             {
304                               /* No.  A simple range, before and disjoint from
305                                  the range going to end of line.  Fill it. */
306                               ADD_RANGE_PAIR (rp, initial, value);
307                             }
308
309                           /* In any case, some fields were selected. */
310                           field_found = 1;
311                         }
312                     }
313                   else
314                     {
315                       /* There is no range going to end of line. */
316                       ADD_RANGE_PAIR (rp, initial, value);
317                       field_found = 1;
318                     }
319                   value = 0;
320                 }
321             }
322           else if (value != 0)
323             {
324               /* A simple field number, not a range. */
325               ADD_RANGE_PAIR (rp, value, value);
326               value = 0;
327               field_found = 1;
328             }
329
330           if (*fieldstr == '\0')
331             {
332               break;
333             }
334
335           fieldstr++;
336         }
337       else if (ISDIGIT (*fieldstr))
338         {
339           /* FIXME: detect overflow?  */
340           value = 10 * value + *fieldstr - '0';
341           fieldstr++;
342         }
343       else
344         FATAL_ERROR (_("invalid byte or field list"));
345     }
346
347   max_range_endpoint = 0;
348   for (i = 0; i < n_rp; i++)
349     {
350       if (rp[i].hi > max_range_endpoint)
351         max_range_endpoint = rp[i].hi;
352     }
353
354   /* Allocate an array large enough so that it may be indexed by
355      the field numbers corresponding to all finite ranges
356      (i.e. `2-6' or `-4', but not `5-') in FIELDSTR.  */
357
358   printable_field = (int *) xmalloc ((max_range_endpoint + 1) * sizeof (int));
359   memset (printable_field, 0, (max_range_endpoint + 1) * sizeof (int));
360
361   /* Set the array entries corresponding to integers in the ranges of RP.  */
362   for (i = 0; i < n_rp; i++)
363     {
364       unsigned int j;
365       for (j = rp[i].lo; j <= rp[i].hi; j++)
366         {
367           printable_field[j] = 1;
368         }
369     }
370
371   free (rp);
372
373   return field_found;
374 }
375
376 /* Read from stream STREAM, printing to standard output any selected bytes.  */
377
378 static void
379 cut_bytes (FILE *stream)
380 {
381   unsigned int byte_idx;        /* Number of chars in the line so far. */
382
383   byte_idx = 0;
384   while (1)
385     {
386       register int c;           /* Each character from the file. */
387
388       c = getc (stream);
389
390       if (c == '\n')
391         {
392           putchar ('\n');
393           byte_idx = 0;
394         }
395       else if (c == EOF)
396         {
397           if (byte_idx > 0)
398             putchar ('\n');
399           break;
400         }
401       else
402         {
403           ++byte_idx;
404           if (print_kth (byte_idx))
405             {
406               putchar (c);
407             }
408         }
409     }
410 }
411
412 /* Read from stream STREAM, printing to standard output any selected fields.  */
413
414 static void
415 cut_fields (FILE *stream)
416 {
417   int c;
418   unsigned int field_idx;
419   int found_any_selected_field;
420   int buffer_first_field;
421   int empty_input;
422
423   found_any_selected_field = 0;
424   field_idx = 1;
425
426   c = getc (stream);
427   empty_input = (c == EOF);
428   if (c != EOF)
429     ungetc (c, stream);
430
431   /* To support the semantics of the -s flag, we may have to buffer
432      all of the first field to determine whether it is `delimited.'
433      But that is unnecessary if all non-delimited lines must be printed
434      and the first field has been selected, or if non-delimited lines
435      must be suppressed and the first field has *not* been selected.
436      That is because a non-delimited line has exactly one field.  */
437   buffer_first_field = (suppress_non_delimited ^ !print_kth (1));
438
439   while (1)
440     {
441       if (field_idx == 1 && buffer_first_field)
442         {
443           int len;
444
445           len = getstr (&field_1_buffer, &field_1_bufsize, stream,
446                         delim, '\n', 0);
447           if (len < 0)
448             {
449               if (ferror (stream) || feof (stream))
450                 break;
451               xalloc_die ();
452             }
453
454           assert (len != 0);
455
456           /* If the first field extends to the end of line (it is not
457              delimited) and we are printing all non-delimited lines,
458              print this one.  */
459           if ((unsigned char) field_1_buffer[len - 1] != delim)
460             {
461               if (suppress_non_delimited)
462                 {
463                   /* Empty.  */
464                 }
465               else
466                 {
467                   fwrite (field_1_buffer, sizeof (char), len, stdout);
468                   /* Make sure the output line is newline terminated.  */
469                   if (field_1_buffer[len - 1] != '\n')
470                     putchar ('\n');
471                 }
472               continue;
473             }
474           if (print_kth (1))
475             {
476               /* Print the field, but not the trailing delimiter.  */
477               fwrite (field_1_buffer, sizeof (char), len - 1, stdout);
478               found_any_selected_field = 1;
479             }
480           ++field_idx;
481         }
482
483       if (c != EOF)
484         {
485           if (print_kth (field_idx))
486             {
487               if (found_any_selected_field)
488                 {
489                   fwrite (output_delimiter_string, sizeof (char),
490                           output_delimiter_length, stdout);
491                 }
492               found_any_selected_field = 1;
493
494               while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
495                 {
496                   putchar (c);
497                 }
498             }
499           else
500             {
501               while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
502                 {
503                   /* Empty.  */
504                 }
505             }
506         }
507
508       if (c == '\n')
509         {
510           c = getc (stream);
511           if (c != EOF)
512             {
513               ungetc (c, stream);
514               c = '\n';
515             }
516         }
517
518       if (c == delim)
519         ++field_idx;
520       else if (c == '\n' || c == EOF)
521         {
522           if (found_any_selected_field
523               || (!empty_input && !(suppress_non_delimited && field_idx == 1)))
524             putchar ('\n');
525           if (c == EOF)
526             break;
527           field_idx = 1;
528           found_any_selected_field = 0;
529         }
530     }
531 }
532
533 static void
534 cut_stream (FILE *stream)
535 {
536   if (operating_mode == byte_mode)
537     cut_bytes (stream);
538   else
539     cut_fields (stream);
540 }
541
542 /* Process file FILE to standard output.
543    Return 0 if successful, 1 if not. */
544
545 static int
546 cut_file (char *file)
547 {
548   FILE *stream;
549
550   if (STREQ (file, "-"))
551     {
552       have_read_stdin = 1;
553       stream = stdin;
554     }
555   else
556     {
557       stream = fopen (file, "r");
558       if (stream == NULL)
559         {
560           error (0, errno, "%s", file);
561           return 1;
562         }
563     }
564
565   cut_stream (stream);
566
567   if (ferror (stream))
568     {
569       error (0, errno, "%s", file);
570       return 1;
571     }
572   if (STREQ (file, "-"))
573     clearerr (stream);          /* Also clear EOF. */
574   else if (fclose (stream) == EOF)
575     {
576       error (0, errno, "%s", file);
577       return 1;
578     }
579   return 0;
580 }
581
582 int
583 main (int argc, char **argv)
584 {
585   int optc, exit_status = 0;
586   int delim_specified = 0;
587
588   program_name = argv[0];
589   setlocale (LC_ALL, "");
590   bindtextdomain (PACKAGE, LOCALEDIR);
591   textdomain (PACKAGE);
592
593   atexit (close_stdout);
594
595   operating_mode = undefined_mode;
596
597   /* By default, all non-delimited lines are printed.  */
598   suppress_non_delimited = 0;
599
600   delim = '\0';
601   have_read_stdin = 0;
602
603   while ((optc = getopt_long (argc, argv, "b:c:d:f:ns", longopts, NULL)) != -1)
604     {
605       switch (optc)
606         {
607         case 0:
608           break;
609
610         case 'b':
611         case 'c':
612           /* Build the byte list. */
613           if (operating_mode != undefined_mode)
614             FATAL_ERROR (_("only one type of list may be specified"));
615           operating_mode = byte_mode;
616           if (set_fields (optarg) == 0)
617             FATAL_ERROR (_("missing list of positions"));
618           break;
619
620         case 'f':
621           /* Build the field list. */
622           if (operating_mode != undefined_mode)
623             FATAL_ERROR (_("only one type of list may be specified"));
624           operating_mode = field_mode;
625           if (set_fields (optarg) == 0)
626             FATAL_ERROR (_("missing list of fields"));
627           break;
628
629         case 'd':
630           /* New delimiter. */
631           /* Interpret -d '' to mean `use the NUL byte as the delimiter.'  */
632           if (optarg[0] != '\0' && optarg[1] != '\0')
633             FATAL_ERROR (_("the delimiter must be a single character"));
634           delim = (unsigned char) optarg[0];
635           delim_specified = 1;
636           break;
637
638         case OUTPUT_DELIMITER_OPTION:
639           /* Interpret --output-delimiter='' to mean
640              `use the NUL byte as the delimiter.'  */
641           output_delimiter_length = (optarg[0] == '\0'
642                                      ? 1 : strlen (optarg));
643           output_delimiter_string = xstrdup (optarg);
644           break;
645
646         case 'n':
647           break;
648
649         case 's':
650           suppress_non_delimited = 1;
651           break;
652
653         case_GETOPT_HELP_CHAR;
654
655         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
656
657         default:
658           usage (2);
659         }
660     }
661
662   if (operating_mode == undefined_mode)
663     FATAL_ERROR (_("you must specify a list of bytes, characters, or fields"));
664
665   if (delim != '\0' && operating_mode != field_mode)
666     FATAL_ERROR (_("a delimiter may be specified only when operating on fields"));
667
668   if (suppress_non_delimited && operating_mode != field_mode)
669     FATAL_ERROR (_("suppressing non-delimited lines makes sense\n\
670 \tonly when operating on fields"));
671
672   if (!delim_specified)
673     delim = '\t';
674
675   if (output_delimiter_string == NULL)
676     {
677       static char dummy[2];
678       dummy[0] = delim;
679       dummy[1] = '\0';
680       output_delimiter_string = dummy;
681       output_delimiter_length = 1;
682     }
683
684   if (optind == argc)
685     exit_status |= cut_file ("-");
686   else
687     for (; optind < argc; optind++)
688       exit_status |= cut_file (argv[optind]);
689
690   if (have_read_stdin && fclose (stdin) == EOF)
691     {
692       error (0, errno, "-");
693       exit_status = 1;
694     }
695
696   exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
697 }