*** empty log message ***
[coreutils.git] / src / cut.c
blob83fd4efc443add2fcd7481a401105eb37d87a3fe
1 /* cut - remove parts of lines of files
2 Copyright (C) 1997-2004 Free Software Foundation, Inc.
3 Copyright (C) 1984 David M. Ihnat
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 2, or (at your option)
8 any later version.
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.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software Foundation,
17 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
19 /* Written by David Ihnat. */
21 /* POSIX changes, bug fixes, long-named options, and cleanup
22 by David MacKenzie <djm@gnu.ai.mit.edu>.
24 Rewrite cut_fields and cut_bytes -- Jim Meyering. */
26 #include <config.h>
28 #include <stdio.h>
29 #include <assert.h>
30 #include <getopt.h>
31 #include <sys/types.h>
32 #include "system.h"
34 #include "error.h"
35 #include "getndelim2.h"
36 #include "hash.h"
37 #include "quote.h"
38 #include "xstrndup.h"
40 /* The official name of this program (e.g., no `g' prefix). */
41 #define PROGRAM_NAME "cut"
43 #define AUTHORS "David Ihnat", "David MacKenzie", "Jim Meyering"
45 #define FATAL_ERROR(Message) \
46 do \
47 { \
48 error (0, 0, (Message)); \
49 usage (EXIT_FAILURE); \
50 } \
51 while (0)
53 /* Append LOW, HIGH to the list RP of range pairs, allocating additional
54 space if necessary. Update local variable N_RP. When allocating,
55 update global variable N_RP_ALLOCATED. */
57 #define ADD_RANGE_PAIR(rp, low, high) \
58 do \
59 { \
60 if (n_rp >= n_rp_allocated) \
61 { \
62 (rp) = x2nrealloc (rp, &n_rp_allocated, sizeof *(rp)); \
63 } \
64 rp[n_rp].lo = (low); \
65 rp[n_rp].hi = (high); \
66 ++n_rp; \
67 } \
68 while (0)
70 struct range_pair
72 size_t lo;
73 size_t hi;
76 /* This buffer is used to support the semantics of the -s option
77 (or lack of same) when the specified field list includes (does
78 not include) the first field. In both of those cases, the entire
79 first field must be read into this buffer to determine whether it
80 is followed by a delimiter or a newline before any of it may be
81 output. Otherwise, cut_fields can do the job without using this
82 buffer. */
83 static char *field_1_buffer;
85 /* The number of bytes allocated for FIELD_1_BUFFER. */
86 static size_t field_1_bufsize;
88 /* The largest field or byte index used as an endpoint of a closed
89 or degenerate range specification; this doesn't include the starting
90 index of right-open-ended ranges. For example, with either range spec
91 `2-5,9-', `2-3,5,9-' this variable would be set to 5. */
92 static size_t max_range_endpoint;
94 /* If nonzero, this is the index of the first field in a range that goes
95 to end of line. */
96 static size_t eol_range_start;
98 /* This is a bit vector.
99 In byte mode, which bytes to output.
100 In field mode, which DELIM-separated fields to output.
101 Both bytes and fields are numbered starting with 1,
102 so the zeroth bit of this array is unused.
103 A field or byte K has been selected if
104 (K <= MAX_RANGE_ENDPOINT and is_printable_field(K))
105 || (EOL_RANGE_START > 0 && K >= EOL_RANGE_START). */
106 static unsigned char *printable_field;
108 enum operating_mode
110 undefined_mode,
112 /* Output characters that are in the given bytes. */
113 byte_mode,
115 /* Output the given delimeter-separated fields. */
116 field_mode
119 /* The name this program was run with. */
120 char *program_name;
122 static enum operating_mode operating_mode;
124 /* If true do not output lines containing no delimeter characters.
125 Otherwise, all such lines are printed. This option is valid only
126 with field mode. */
127 static bool suppress_non_delimited;
129 /* The delimeter character for field mode. */
130 static unsigned char delim;
132 /* True if the --output-delimiter=STRING option was specified. */
133 static bool output_delimiter_specified;
135 /* The length of output_delimiter_string. */
136 static size_t output_delimiter_length;
138 /* The output field separator string. Defaults to the 1-character
139 string consisting of the input delimiter. */
140 static char *output_delimiter_string;
142 /* True if we have ever read standard input. */
143 static bool have_read_stdin;
145 #define HT_RANGE_START_INDEX_INITIAL_CAPACITY 31
147 /* The set of range-start indices. For example, given a range-spec list like
148 `-b1,3-5,4-9,15-', the following indices will be recorded here: 1, 3, 15.
149 Note that although `4' looks like a range-start index, it is in the middle
150 of the `3-5' range, so it doesn't count.
151 This table is created/used IFF output_delimiter_specified is set. */
152 static Hash_table *range_start_ht;
154 /* For long options that have no equivalent short option, use a
155 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
156 enum
158 OUTPUT_DELIMITER_OPTION = CHAR_MAX + 1
161 static struct option const longopts[] =
163 {"bytes", required_argument, 0, 'b'},
164 {"characters", required_argument, 0, 'c'},
165 {"fields", required_argument, 0, 'f'},
166 {"delimiter", required_argument, 0, 'd'},
167 {"only-delimited", no_argument, 0, 's'},
168 {"output-delimiter", required_argument, 0, OUTPUT_DELIMITER_OPTION},
169 {GETOPT_HELP_OPTION_DECL},
170 {GETOPT_VERSION_OPTION_DECL},
171 {0, 0, 0, 0}
174 void
175 usage (int status)
177 if (status != EXIT_SUCCESS)
178 fprintf (stderr, _("Try `%s --help' for more information.\n"),
179 program_name);
180 else
182 printf (_("\
183 Usage: %s [OPTION]... [FILE]...\n\
185 program_name);
186 fputs (_("\
187 Print selected parts of lines from each FILE to standard output.\n\
189 "), stdout);
190 fputs (_("\
191 Mandatory arguments to long options are mandatory for short options too.\n\
192 "), stdout);
193 fputs (_("\
194 -b, --bytes=LIST output only these bytes\n\
195 -c, --characters=LIST output only these characters\n\
196 -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter\n\
197 "), stdout);
198 fputs (_("\
199 -f, --fields=LIST output only these fields; also print any line\n\
200 that contains no delimiter character, unless\n\
201 the -s option is specified\n\
202 -n (ignored)\n\
203 "), stdout);
204 fputs (_("\
205 -s, --only-delimited do not print lines not containing delimiters\n\
206 --output-delimiter=STRING use STRING as the output delimiter\n\
207 the default is to use the input delimiter\n\
208 "), stdout);
209 fputs (HELP_OPTION_DESCRIPTION, stdout);
210 fputs (VERSION_OPTION_DESCRIPTION, stdout);
211 fputs (_("\
213 Use one, and only one of -b, -c or -f. Each LIST is made up of one\n\
214 range, or many ranges separated by commas. Each range is one of:\n\
216 N N'th byte, character or field, counted from 1\n\
217 N- from N'th byte, character or field, to end of line\n\
218 N-M from N'th to M'th (included) byte, character or field\n\
219 -M from first to M'th (included) byte, character or field\n\
221 With no FILE, or when FILE is -, read standard input.\n\
222 "), stdout);
223 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
225 exit (status);
228 static inline void
229 mark_printable_field (size_t i)
231 size_t n = i / CHAR_BIT;
232 printable_field[n] |= (1 << (i % CHAR_BIT));
235 static inline bool
236 is_printable_field (size_t i)
238 size_t n = i / CHAR_BIT;
239 return (printable_field[n] >> (i % CHAR_BIT)) & 1;
242 static size_t
243 hash_int (const void *x, size_t tablesize)
245 uintptr_t y = (uintptr_t) x;
246 return y % tablesize;
249 static bool
250 hash_compare_ints (void const *x, void const *y)
252 return (x == y) ? true : false;
255 static bool
256 is_range_start_index (size_t i)
258 return hash_lookup (range_start_ht, (void *) i) ? true : false;
261 /* Return nonzero if the K'th field or byte is printable.
262 When returning nonzero, if RANGE_START is non-NULL,
263 set *RANGE_START to true if K is the beginning of a range, and to
264 false otherwise. */
266 static bool
267 print_kth (size_t k, bool *range_start)
269 if (0 < eol_range_start && eol_range_start <= k)
271 if (range_start)
272 *range_start = (k == eol_range_start);
273 return true;
276 if (k <= max_range_endpoint && is_printable_field (k))
278 if (range_start)
279 *range_start = is_range_start_index (k);
280 return true;
283 return false;
286 /* Given the list of field or byte range specifications FIELDSTR, set
287 MAX_RANGE_ENDPOINT and allocate and initialize the PRINTABLE_FIELD
288 array. If there is a right-open-ended range, set EOL_RANGE_START
289 to its starting index. FIELDSTR should be composed of one or more
290 numbers or ranges of numbers, separated by blanks or commas.
291 Incomplete ranges may be given: `-m' means `1-m'; `n-' means `n'
292 through end of line. Return true if FIELDSTR contains at least
293 one field specification, false otherwise. */
295 /* FIXME-someday: What if the user wants to cut out the 1,000,000-th
296 field of some huge input file? This function shouldn't have to
297 allocate a table of a million bits just so we can test every
298 field < 10^6 with an array dereference. Instead, consider using
299 an adaptive approach: if the range of selected fields is too large,
300 but only a few fields/byte-offsets are actually selected, use a
301 hash table. If the range of selected fields is too large, and
302 too many are selected, then resort to using the range-pairs (the
303 `rp' array) directly. */
305 static bool
306 set_fields (const char *fieldstr)
308 size_t initial = 1; /* Value of first number in a range. */
309 size_t value = 0; /* If nonzero, a number being accumulated. */
310 bool dash_found = false; /* True if a '-' is found in this field. */
311 bool field_found = false; /* True if at least one field spec
312 has been processed. */
314 struct range_pair *rp = NULL;
315 size_t n_rp = 0;
316 size_t n_rp_allocated = 0;
317 size_t i;
318 bool in_digits = false;
320 /* Collect and store in RP the range end points.
321 It also sets EOL_RANGE_START if appropriate. */
323 for (;;)
325 if (*fieldstr == '-')
327 in_digits = false;
328 /* Starting a range. */
329 if (dash_found)
330 FATAL_ERROR (_("invalid byte or field list"));
331 dash_found = true;
332 fieldstr++;
334 if (value)
336 initial = value;
337 value = 0;
339 else
340 initial = 1;
342 else if (*fieldstr == ',' || ISBLANK (*fieldstr) || *fieldstr == '\0')
344 in_digits = false;
345 /* Ending the string, or this field/byte sublist. */
346 if (dash_found)
348 dash_found = false;
350 /* A range. Possibilites: -n, m-n, n-.
351 In any case, `initial' contains the start of the range. */
352 if (value == 0)
354 /* `n-'. From `initial' to end of line. */
355 eol_range_start = initial;
356 field_found = true;
358 else
360 /* `m-n' or `-n' (1-n). */
361 if (value < initial)
362 FATAL_ERROR (_("invalid byte or field list"));
364 /* Is there already a range going to end of line? */
365 if (eol_range_start != 0)
367 /* Yes. Is the new sequence already contained
368 in the old one? If so, no processing is
369 necessary. */
370 if (initial < eol_range_start)
372 /* No, the new sequence starts before the
373 old. Does the old range going to end of line
374 extend into the new range? */
375 if (eol_range_start <= value)
377 /* Yes. Simply move the end of line marker. */
378 eol_range_start = initial;
380 else
382 /* No. A simple range, before and disjoint from
383 the range going to end of line. Fill it. */
384 ADD_RANGE_PAIR (rp, initial, value);
387 /* In any case, some fields were selected. */
388 field_found = true;
391 else
393 /* There is no range going to end of line. */
394 ADD_RANGE_PAIR (rp, initial, value);
395 field_found = true;
397 value = 0;
400 else if (value != 0)
402 /* A simple field number, not a range. */
403 ADD_RANGE_PAIR (rp, value, value);
404 value = 0;
405 field_found = true;
408 if (*fieldstr == '\0')
410 break;
413 fieldstr++;
415 else if (ISDIGIT (*fieldstr))
417 size_t new_v;
418 /* Record beginning of digit string, in case we have to
419 complain about it. */
420 static char const *num_start;
421 if (!in_digits || !num_start)
422 num_start = fieldstr;
423 in_digits = true;
425 /* Detect overflow. */
426 new_v = 10 * value + *fieldstr - '0';
427 if (SIZE_MAX / 10 < value || new_v < value * 10)
429 /* In case the user specified -c4294967296-22,
430 complain only about the first number. */
431 /* Determine the length of the offending number. */
432 size_t len = strspn (num_start, "0123456789");
433 char *bad_num = xstrndup (num_start, len);
434 if (operating_mode == byte_mode)
435 error (0, 0,
436 _("byte offset %s is too large"), quote (bad_num));
437 else
438 error (0, 0,
439 _("field number %s is too large"), quote (bad_num));
440 free (bad_num);
441 exit (EXIT_FAILURE);
443 value = new_v;
445 fieldstr++;
447 else
448 FATAL_ERROR (_("invalid byte or field list"));
451 max_range_endpoint = 0;
452 for (i = 0; i < n_rp; i++)
454 if (rp[i].hi > max_range_endpoint)
455 max_range_endpoint = rp[i].hi;
458 /* Allocate an array large enough so that it may be indexed by
459 the field numbers corresponding to all finite ranges
460 (i.e. `2-6' or `-4', but not `5-') in FIELDSTR. */
462 printable_field = xzalloc (max_range_endpoint / CHAR_BIT + 1);
464 /* Set the array entries corresponding to integers in the ranges of RP. */
465 for (i = 0; i < n_rp; i++)
467 size_t j;
468 for (j = rp[i].lo; j <= rp[i].hi; j++)
470 mark_printable_field (j);
474 if (output_delimiter_specified)
476 /* Record the range-start indices. */
477 for (i = 0; i < n_rp; i++)
479 size_t j;
480 for (j = rp[i].lo; j <= rp[i].hi; j++)
482 if (0 < j && is_printable_field (j)
483 && !is_printable_field (j - 1))
485 /* Record the fact that `j' is a range-start index. */
486 void *ent_from_table = hash_insert (range_start_ht,
487 (void*) j);
488 if (ent_from_table == NULL)
490 /* Insertion failed due to lack of memory. */
491 xalloc_die ();
493 assert ((size_t) ent_from_table == j);
499 free (rp);
501 return field_found;
504 /* Read from stream STREAM, printing to standard output any selected bytes. */
506 static void
507 cut_bytes (FILE *stream)
509 size_t byte_idx; /* Number of bytes in the line so far. */
510 /* Whether to begin printing delimiters between ranges for the current line.
511 Set after we've begun printing data corresponding to the first range. */
512 bool print_delimiter;
514 byte_idx = 0;
515 print_delimiter = false;
516 while (1)
518 register int c; /* Each character from the file. */
520 c = getc (stream);
522 if (c == '\n')
524 putchar ('\n');
525 byte_idx = 0;
526 print_delimiter = false;
528 else if (c == EOF)
530 if (byte_idx > 0)
531 putchar ('\n');
532 break;
534 else
536 bool range_start;
537 bool *rs = output_delimiter_specified ? &range_start : NULL;
538 if (print_kth (++byte_idx, rs))
540 if (rs && *rs && print_delimiter)
542 fwrite (output_delimiter_string, sizeof (char),
543 output_delimiter_length, stdout);
545 print_delimiter = true;
546 putchar (c);
552 /* Read from stream STREAM, printing to standard output any selected fields. */
554 static void
555 cut_fields (FILE *stream)
557 int c;
558 size_t field_idx = 1;
559 bool found_any_selected_field = false;
560 bool buffer_first_field;
562 c = getc (stream);
563 if (c == EOF)
564 return;
566 ungetc (c, stream);
568 /* To support the semantics of the -s flag, we may have to buffer
569 all of the first field to determine whether it is `delimited.'
570 But that is unnecessary if all non-delimited lines must be printed
571 and the first field has been selected, or if non-delimited lines
572 must be suppressed and the first field has *not* been selected.
573 That is because a non-delimited line has exactly one field. */
574 buffer_first_field = (suppress_non_delimited ^ !print_kth (1, NULL));
576 while (1)
578 if (field_idx == 1 && buffer_first_field)
580 ssize_t len;
581 size_t n_bytes;
583 len = getndelim2 (&field_1_buffer, &field_1_bufsize, SIZE_MAX,
584 stream, delim, '\n', 0);
585 if (len < 0)
587 if (ferror (stream) || feof (stream))
588 break;
589 xalloc_die ();
592 n_bytes = len;
593 assert (n_bytes != 0);
595 /* If the first field extends to the end of line (it is not
596 delimited) and we are printing all non-delimited lines,
597 print this one. */
598 if ((unsigned char) field_1_buffer[n_bytes - 1] != delim)
600 if (suppress_non_delimited)
602 /* Empty. */
604 else
606 fwrite (field_1_buffer, sizeof (char), n_bytes, stdout);
607 /* Make sure the output line is newline terminated. */
608 if (field_1_buffer[n_bytes - 1] != '\n')
609 putchar ('\n');
611 continue;
613 if (print_kth (1, NULL))
615 /* Print the field, but not the trailing delimiter. */
616 fwrite (field_1_buffer, sizeof (char), n_bytes - 1, stdout);
617 found_any_selected_field = true;
619 ++field_idx;
622 if (c != EOF)
624 if (print_kth (field_idx, NULL))
626 if (found_any_selected_field)
628 fwrite (output_delimiter_string, sizeof (char),
629 output_delimiter_length, stdout);
631 found_any_selected_field = true;
633 while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
635 putchar (c);
638 else
640 while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
642 /* Empty. */
647 if (c == '\n')
649 c = getc (stream);
650 if (c != EOF)
652 ungetc (c, stream);
653 c = '\n';
657 if (c == delim)
658 ++field_idx;
659 else if (c == '\n' || c == EOF)
661 if (found_any_selected_field
662 || !(suppress_non_delimited && field_idx == 1))
663 putchar ('\n');
664 if (c == EOF)
665 break;
666 field_idx = 1;
667 found_any_selected_field = false;
672 static void
673 cut_stream (FILE *stream)
675 if (operating_mode == byte_mode)
676 cut_bytes (stream);
677 else
678 cut_fields (stream);
681 /* Process file FILE to standard output.
682 Return 0 if successful, 1 if not. */
684 static int
685 cut_file (char *file)
687 FILE *stream;
689 if (STREQ (file, "-"))
691 have_read_stdin = true;
692 stream = stdin;
694 else
696 stream = fopen (file, "r");
697 if (stream == NULL)
699 error (0, errno, "%s", file);
700 return 1;
704 cut_stream (stream);
706 if (ferror (stream))
708 error (0, errno, "%s", file);
709 return 1;
711 if (STREQ (file, "-"))
712 clearerr (stream); /* Also clear EOF. */
713 else if (fclose (stream) == EOF)
715 error (0, errno, "%s", file);
716 return 1;
718 return 0;
722 main (int argc, char **argv)
724 int optc, exit_status = 0;
725 bool delim_specified = false;
726 char *spec_list_string IF_LINT(= NULL);
728 initialize_main (&argc, &argv);
729 program_name = argv[0];
730 setlocale (LC_ALL, "");
731 bindtextdomain (PACKAGE, LOCALEDIR);
732 textdomain (PACKAGE);
734 atexit (close_stdout);
736 operating_mode = undefined_mode;
738 /* By default, all non-delimited lines are printed. */
739 suppress_non_delimited = false;
741 delim = '\0';
742 have_read_stdin = false;
744 while ((optc = getopt_long (argc, argv, "b:c:d:f:ns", longopts, NULL)) != -1)
746 switch (optc)
748 case 0:
749 break;
751 case 'b':
752 case 'c':
753 /* Build the byte list. */
754 if (operating_mode != undefined_mode)
755 FATAL_ERROR (_("only one type of list may be specified"));
756 operating_mode = byte_mode;
757 spec_list_string = optarg;
758 break;
760 case 'f':
761 /* Build the field list. */
762 if (operating_mode != undefined_mode)
763 FATAL_ERROR (_("only one type of list may be specified"));
764 operating_mode = field_mode;
765 spec_list_string = optarg;
766 break;
768 case 'd':
769 /* New delimiter. */
770 /* Interpret -d '' to mean `use the NUL byte as the delimiter.' */
771 if (optarg[0] != '\0' && optarg[1] != '\0')
772 FATAL_ERROR (_("the delimiter must be a single character"));
773 delim = optarg[0];
774 delim_specified = true;
775 break;
777 case OUTPUT_DELIMITER_OPTION:
778 output_delimiter_specified = true;
779 /* Interpret --output-delimiter='' to mean
780 `use the NUL byte as the delimiter.' */
781 output_delimiter_length = (optarg[0] == '\0'
782 ? 1 : strlen (optarg));
783 output_delimiter_string = xstrdup (optarg);
784 break;
786 case 'n':
787 break;
789 case 's':
790 suppress_non_delimited = true;
791 break;
793 case_GETOPT_HELP_CHAR;
795 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
797 default:
798 usage (EXIT_FAILURE);
802 if (operating_mode == undefined_mode)
803 FATAL_ERROR (_("you must specify a list of bytes, characters, or fields"));
805 if (delim != '\0' && operating_mode != field_mode)
806 FATAL_ERROR (_("an input delimiter may be specified only\
807 when operating on fields"));
809 if (suppress_non_delimited && operating_mode != field_mode)
810 FATAL_ERROR (_("suppressing non-delimited lines makes sense\n\
811 \tonly when operating on fields"));
813 if (output_delimiter_specified)
815 range_start_ht = hash_initialize (HT_RANGE_START_INDEX_INITIAL_CAPACITY,
816 NULL, hash_int,
817 hash_compare_ints, NULL);
818 if (range_start_ht == NULL)
819 xalloc_die ();
823 if (! set_fields (spec_list_string))
825 if (operating_mode == field_mode)
826 FATAL_ERROR (_("missing list of fields"));
827 else
828 FATAL_ERROR (_("missing list of positions"));
831 if (!delim_specified)
832 delim = '\t';
834 if (output_delimiter_string == NULL)
836 static char dummy[2];
837 dummy[0] = delim;
838 dummy[1] = '\0';
839 output_delimiter_string = dummy;
840 output_delimiter_length = 1;
843 if (optind == argc)
844 exit_status |= cut_file ("-");
845 else
846 for (; optind < argc; optind++)
847 exit_status |= cut_file (argv[optind]);
849 if (range_start_ht)
850 hash_free (range_start_ht);
852 if (have_read_stdin && fclose (stdin) == EOF)
854 error (0, errno, "-");
855 exit_status = 1;
858 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);