*** empty log message ***
[coreutils.git] / src / cut.c
blobd9592d16b80ae2b016fceb971c839cca330691cc
1 /* cut - remove parts of lines of files
2 Copyright (C) 1984, 1997, 1998, 1999, 2000, 2001 by David M. Ihnat
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.
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.
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. */
18 /* Written by David Ihnat. */
20 /* POSIX changes, bug fixes, long-named options, and cleanup
21 by David MacKenzie <djm@gnu.ai.mit.edu>.
23 Rewrite cut_fields and cut_bytes -- Jim Meyering. */
25 #include <config.h>
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"
36 /* The official name of this program (e.g., no `g' prefix). */
37 #define PROGRAM_NAME "cut"
39 #define AUTHORS N_ ("David Ihnat, David MacKenzie, and Jim Meyering")
41 #define FATAL_ERROR(Message) \
42 do \
43 { \
44 error (0, 0, (Message)); \
45 usage (2); \
46 } \
47 while (0)
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. */
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)
68 struct range_pair
70 unsigned int lo;
71 unsigned int hi;
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;
83 /* The number of bytes allocated for FIELD_1_BUFFER. */
84 static size_t field_1_bufsize;
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;
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;
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;
105 enum operating_mode
107 undefined_mode,
109 /* Output characters that are in the given bytes. */
110 byte_mode,
112 /* Output the given delimeter-separated fields. */
113 field_mode
116 /* The name this program was run with. */
117 char *program_name;
119 static enum operating_mode operating_mode;
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;
126 /* The delimeter character for field mode. */
127 static int delim;
129 /* The length of output_delimiter_string. */
130 static size_t output_delimiter_length;
132 /* The output field separator string. Defaults to the 1-character
133 string consisting of the input delimiter. */
134 static char *output_delimiter_string;
136 /* Nonzero if we have ever read standard input. */
137 static int have_read_stdin;
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
143 OUTPUT_DELIMITER_OPTION = CHAR_MAX + 1
146 static struct option const longopts[] =
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}
159 void
160 usage (int status)
162 if (status != 0)
163 fprintf (stderr, _("Try `%s --help' for more information.\n"),
164 program_name);
165 else
167 printf (_("\
168 Usage: %s [OPTION]... [FILE]...\n\
170 program_name);
171 fputs (_("\
172 Print selected parts of lines from each FILE to standard output.\n\
174 "), stdout);
175 fputs (_("\
176 Mandatory arguments to long options are mandatory for short options too.\n\
177 "), stdout);
178 fputs (_("\
179 -b, --bytes=LIST output only these bytes\n\
180 -c, --characters=LIST output only these characters\n\
181 -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter\n\
182 "), stdout);
183 fputs (_("\
184 -f, --fields=LIST output only these fields; also print any line\n\
185 that contains no delimiter character, unless\n\
186 the -s option is specified\n\
187 -n (ignored)\n\
188 "), stdout);
189 fputs (_("\
190 -s, --only-delimited do not print lines not containing delimiters\n\
191 --output-delimiter=STRING use STRING as the output delimiter\n\
192 the default is to use the input delimiter\n\
193 "), stdout);
194 fputs (HELP_OPTION_DESCRIPTION, stdout);
195 fputs (VERSION_OPTION_DESCRIPTION, stdout);
196 fputs (_("\
198 Use one, and only one of -b, -c or -f. Each LIST is made up of one\n\
199 range, or many ranges separated by commas. Each range is one of:\n\
201 N N'th byte, character or field, counted from 1\n\
202 N- from N'th byte, character or field, to end of line\n\
203 N-M from N'th to M'th (included) byte, character or field\n\
204 -M from first to M'th (included) byte, character or field\n\
206 With no FILE, or when FILE is -, read standard input.\n\
207 "), stdout);
208 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
210 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
213 static int
214 print_kth (unsigned int k)
216 return ((0 < eol_range_start && eol_range_start <= k)
217 || (k <= max_range_endpoint && printable_field[k]));
220 /* Given the list of field or byte range specifications FIELDSTR, set
221 MAX_RANGE_ENDPOINT and allocate and initialize the PRINTABLE_FIELD
222 array. If there is a right-open-ended range, set EOL_RANGE_START
223 to its starting index. FIELDSTR should be composed of one or more
224 numbers or ranges of numbers, separated by blanks or commas.
225 Incomplete ranges may be given: `-m' means `1-m'; `n-' means `n'
226 through end of line. Return nonzero if FIELDSTR contains at least
227 one field specification, zero otherwise. */
229 /* FIXME-someday: What if the user wants to cut out the 1,000,000-th field
230 of some huge input file? This function shouldn't have to alloate a table
231 of a million ints just so we can test every field < 10^6 with an array
232 dereference. Instead, consider using a dynamic hash table. It would be
233 simpler and nearly as good a solution to use a 32K x 4-byte table with
234 one bit per field index instead of a whole `int' per index. */
236 static int
237 set_fields (const char *fieldstr)
239 unsigned int initial = 1; /* Value of first number in a range. */
240 unsigned int value = 0; /* If nonzero, a number being accumulated. */
241 int dash_found = 0; /* Nonzero if a '-' is found in this field. */
242 int field_found = 0; /* Non-zero if at least one field spec
243 has been processed. */
245 struct range_pair *rp;
246 unsigned int n_rp;
247 unsigned int n_rp_allocated;
248 unsigned int i;
250 n_rp = 0;
251 n_rp_allocated = 16;
252 rp = (struct range_pair *) xmalloc (n_rp_allocated * sizeof (*rp));
254 /* Collect and store in RP the range end points.
255 It also sets EOL_RANGE_START if appropriate. */
257 for (;;)
259 if (*fieldstr == '-')
261 /* Starting a range. */
262 if (dash_found)
263 FATAL_ERROR (_("invalid byte or field list"));
264 dash_found++;
265 fieldstr++;
267 if (value)
269 initial = value;
270 value = 0;
272 else
273 initial = 1;
275 else if (*fieldstr == ',' || ISBLANK (*fieldstr) || *fieldstr == '\0')
277 /* Ending the string, or this field/byte sublist. */
278 if (dash_found)
280 dash_found = 0;
282 /* A range. Possibilites: -n, m-n, n-.
283 In any case, `initial' contains the start of the range. */
284 if (value == 0)
286 /* `n-'. From `initial' to end of line. */
287 eol_range_start = initial;
288 field_found = 1;
290 else
292 /* `m-n' or `-n' (1-n). */
293 if (value < initial)
294 FATAL_ERROR (_("invalid byte or field list"));
296 /* Is there already a range going to end of line? */
297 if (eol_range_start != 0)
299 /* Yes. Is the new sequence already contained
300 in the old one? If so, no processing is
301 necessary. */
302 if (initial < eol_range_start)
304 /* No, the new sequence starts before the
305 old. Does the old range going to end of line
306 extend into the new range? */
307 if (value + 1 >= eol_range_start)
309 /* Yes. Simply move the end of line marker. */
310 eol_range_start = initial;
312 else
314 /* No. A simple range, before and disjoint from
315 the range going to end of line. Fill it. */
316 ADD_RANGE_PAIR (rp, initial, value);
319 /* In any case, some fields were selected. */
320 field_found = 1;
323 else
325 /* There is no range going to end of line. */
326 ADD_RANGE_PAIR (rp, initial, value);
327 field_found = 1;
329 value = 0;
332 else if (value != 0)
334 /* A simple field number, not a range. */
335 ADD_RANGE_PAIR (rp, value, value);
336 value = 0;
337 field_found = 1;
340 if (*fieldstr == '\0')
342 break;
345 fieldstr++;
347 else if (ISDIGIT (*fieldstr))
349 /* FIXME: detect overflow? */
350 value = 10 * value + *fieldstr - '0';
351 fieldstr++;
353 else
354 FATAL_ERROR (_("invalid byte or field list"));
357 max_range_endpoint = 0;
358 for (i = 0; i < n_rp; i++)
360 if (rp[i].hi > max_range_endpoint)
361 max_range_endpoint = rp[i].hi;
364 /* Allocate an array large enough so that it may be indexed by
365 the field numbers corresponding to all finite ranges
366 (i.e. `2-6' or `-4', but not `5-') in FIELDSTR. */
368 printable_field = (int *) xmalloc ((max_range_endpoint + 1) * sizeof (int));
369 memset (printable_field, 0, (max_range_endpoint + 1) * sizeof (int));
371 /* Set the array entries corresponding to integers in the ranges of RP. */
372 for (i = 0; i < n_rp; i++)
374 unsigned int j;
375 for (j = rp[i].lo; j <= rp[i].hi; j++)
377 printable_field[j] = 1;
381 free (rp);
383 return field_found;
386 /* Read from stream STREAM, printing to standard output any selected bytes. */
388 static void
389 cut_bytes (FILE *stream)
391 unsigned int byte_idx; /* Number of chars in the line so far. */
393 byte_idx = 0;
394 while (1)
396 register int c; /* Each character from the file. */
398 c = getc (stream);
400 if (c == '\n')
402 putchar ('\n');
403 byte_idx = 0;
405 else if (c == EOF)
407 if (byte_idx > 0)
408 putchar ('\n');
409 break;
411 else
413 ++byte_idx;
414 if (print_kth (byte_idx))
416 putchar (c);
422 /* Read from stream STREAM, printing to standard output any selected fields. */
424 static void
425 cut_fields (FILE *stream)
427 int c;
428 unsigned int field_idx;
429 int found_any_selected_field;
430 int buffer_first_field;
431 int empty_input;
433 found_any_selected_field = 0;
434 field_idx = 1;
436 c = getc (stream);
437 empty_input = (c == EOF);
438 if (c != EOF)
439 ungetc (c, stream);
441 /* To support the semantics of the -s flag, we may have to buffer
442 all of the first field to determine whether it is `delimited.'
443 But that is unnecessary if all non-delimited lines must be printed
444 and the first field has been selected, or if non-delimited lines
445 must be suppressed and the first field has *not* been selected.
446 That is because a non-delimited line has exactly one field. */
447 buffer_first_field = (suppress_non_delimited ^ !print_kth (1));
449 while (1)
451 if (field_idx == 1 && buffer_first_field)
453 int len;
455 len = getstr (&field_1_buffer, &field_1_bufsize, stream,
456 delim, '\n', 0);
457 if (len < 0)
459 if (ferror (stream) || feof (stream))
460 break;
461 xalloc_die ();
464 assert (len != 0);
466 /* If the first field extends to the end of line (it is not
467 delimited) and we are printing all non-delimited lines,
468 print this one. */
469 if ((unsigned char) field_1_buffer[len - 1] != delim)
471 if (suppress_non_delimited)
473 /* Empty. */
475 else
477 fwrite (field_1_buffer, sizeof (char), len, stdout);
478 /* Make sure the output line is newline terminated. */
479 if (field_1_buffer[len - 1] != '\n')
480 putchar ('\n');
482 continue;
484 if (print_kth (1))
486 /* Print the field, but not the trailing delimiter. */
487 fwrite (field_1_buffer, sizeof (char), len - 1, stdout);
488 found_any_selected_field = 1;
490 ++field_idx;
493 if (c != EOF)
495 if (print_kth (field_idx))
497 if (found_any_selected_field)
499 fwrite (output_delimiter_string, sizeof (char),
500 output_delimiter_length, stdout);
502 found_any_selected_field = 1;
504 while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
506 putchar (c);
509 else
511 while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
513 /* Empty. */
518 if (c == '\n')
520 c = getc (stream);
521 if (c != EOF)
523 ungetc (c, stream);
524 c = '\n';
528 if (c == delim)
529 ++field_idx;
530 else if (c == '\n' || c == EOF)
532 if (found_any_selected_field
533 || (!empty_input && !(suppress_non_delimited && field_idx == 1)))
534 putchar ('\n');
535 if (c == EOF)
536 break;
537 field_idx = 1;
538 found_any_selected_field = 0;
543 static void
544 cut_stream (FILE *stream)
546 if (operating_mode == byte_mode)
547 cut_bytes (stream);
548 else
549 cut_fields (stream);
552 /* Process file FILE to standard output.
553 Return 0 if successful, 1 if not. */
555 static int
556 cut_file (char *file)
558 FILE *stream;
560 if (STREQ (file, "-"))
562 have_read_stdin = 1;
563 stream = stdin;
565 else
567 stream = fopen (file, "r");
568 if (stream == NULL)
570 error (0, errno, "%s", file);
571 return 1;
575 cut_stream (stream);
577 if (ferror (stream))
579 error (0, errno, "%s", file);
580 return 1;
582 if (STREQ (file, "-"))
583 clearerr (stream); /* Also clear EOF. */
584 else if (fclose (stream) == EOF)
586 error (0, errno, "%s", file);
587 return 1;
589 return 0;
593 main (int argc, char **argv)
595 int optc, exit_status = 0;
596 int delim_specified = 0;
598 program_name = argv[0];
599 setlocale (LC_ALL, "");
600 bindtextdomain (PACKAGE, LOCALEDIR);
601 textdomain (PACKAGE);
603 atexit (close_stdout);
605 operating_mode = undefined_mode;
607 /* By default, all non-delimited lines are printed. */
608 suppress_non_delimited = 0;
610 delim = '\0';
611 have_read_stdin = 0;
613 while ((optc = getopt_long (argc, argv, "b:c:d:f:ns", longopts, NULL)) != -1)
615 switch (optc)
617 case 0:
618 break;
620 case 'b':
621 case 'c':
622 /* Build the byte list. */
623 if (operating_mode != undefined_mode)
624 FATAL_ERROR (_("only one type of list may be specified"));
625 operating_mode = byte_mode;
626 if (set_fields (optarg) == 0)
627 FATAL_ERROR (_("missing list of positions"));
628 break;
630 case 'f':
631 /* Build the field list. */
632 if (operating_mode != undefined_mode)
633 FATAL_ERROR (_("only one type of list may be specified"));
634 operating_mode = field_mode;
635 if (set_fields (optarg) == 0)
636 FATAL_ERROR (_("missing list of fields"));
637 break;
639 case 'd':
640 /* New delimiter. */
641 /* Interpret -d '' to mean `use the NUL byte as the delimiter.' */
642 if (optarg[0] != '\0' && optarg[1] != '\0')
643 FATAL_ERROR (_("the delimiter must be a single character"));
644 delim = (unsigned char) optarg[0];
645 delim_specified = 1;
646 break;
648 case OUTPUT_DELIMITER_OPTION:
649 /* Interpret --output-delimiter='' to mean
650 `use the NUL byte as the delimiter.' */
651 output_delimiter_length = (optarg[0] == '\0'
652 ? 1 : strlen (optarg));
653 output_delimiter_string = xstrdup (optarg);
654 break;
656 case 'n':
657 break;
659 case 's':
660 suppress_non_delimited = 1;
661 break;
663 case_GETOPT_HELP_CHAR;
665 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
667 default:
668 usage (2);
672 if (operating_mode == undefined_mode)
673 FATAL_ERROR (_("you must specify a list of bytes, characters, or fields"));
675 if (delim != '\0' && operating_mode != field_mode)
676 FATAL_ERROR (_("a delimiter may be specified only when operating on fields"));
678 if (suppress_non_delimited && operating_mode != field_mode)
679 FATAL_ERROR (_("suppressing non-delimited lines makes sense\n\
680 \tonly when operating on fields"));
682 if (!delim_specified)
683 delim = '\t';
685 if (output_delimiter_string == NULL)
687 static char dummy[2];
688 dummy[0] = delim;
689 dummy[1] = '\0';
690 output_delimiter_string = dummy;
691 output_delimiter_length = 1;
694 if (optind == argc)
695 exit_status |= cut_file ("-");
696 else
697 for (; optind < argc; optind++)
698 exit_status |= cut_file (argv[optind]);
700 if (have_read_stdin && fclose (stdin) == EOF)
702 error (0, errno, "-");
703 exit_status = 1;
706 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);