1 /* cut - remove parts of lines of files
2 Copyright (C) 1997-2013 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 3 of the License, or
8 (at your option) 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, see <http://www.gnu.org/licenses/>. */
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. */
30 #include <sys/types.h>
35 #include "getndelim2.h"
40 /* The official name of this program (e.g., no 'g' prefix). */
41 #define PROGRAM_NAME "cut"
44 proper_name ("David M. Ihnat"), \
45 proper_name ("David MacKenzie"), \
46 proper_name ("Jim Meyering")
48 #define FATAL_ERROR(Message) \
51 error (0, 0, (Message)); \
52 usage (EXIT_FAILURE); \
63 /* Array of `struct range_pair' holding all the finite ranges. */
64 static struct range_pair
*rp
;
66 /* Pointer inside RP. When checking if a byte or field is selected
67 by a finite range, we check if it is between CURRENT_RP.LO
68 and CURRENT_RP.HI. If the byte or field index is greater than
69 CURRENT_RP.HI then we make CURRENT_RP to point to the next range pair. */
70 static struct range_pair
*current_rp
;
72 /* Number of finite ranges specified by the user. */
75 /* Number of `struct range_pair's allocated. */
76 static size_t n_rp_allocated
;
79 /* Append LOW, HIGH to the list RP of range pairs, allocating additional
80 space if necessary. Update global variable N_RP. When allocating,
81 update global variable N_RP_ALLOCATED. */
84 add_range_pair (size_t lo
, size_t hi
)
86 if (n_rp
== n_rp_allocated
)
87 rp
= X2NREALLOC (rp
, &n_rp_allocated
);
93 /* This buffer is used to support the semantics of the -s option
94 (or lack of same) when the specified field list includes (does
95 not include) the first field. In both of those cases, the entire
96 first field must be read into this buffer to determine whether it
97 is followed by a delimiter or a newline before any of it may be
98 output. Otherwise, cut_fields can do the job without using this
100 static char *field_1_buffer
;
102 /* The number of bytes allocated for FIELD_1_BUFFER. */
103 static size_t field_1_bufsize
;
109 /* Output characters that are in the given bytes. */
112 /* Output the given delimeter-separated fields. */
116 static enum operating_mode operating_mode
;
118 /* If true do not output lines containing no delimeter characters.
119 Otherwise, all such lines are printed. This option is valid only
121 static bool suppress_non_delimited
;
123 /* If true, print all bytes, characters, or fields _except_
124 those that were specified. */
125 static bool complement
;
127 /* The delimeter character for field mode. */
128 static unsigned char delim
;
130 /* True if the --output-delimiter=STRING option was specified. */
131 static bool output_delimiter_specified
;
133 /* The length of output_delimiter_string. */
134 static size_t output_delimiter_length
;
136 /* The output field separator string. Defaults to the 1-character
137 string consisting of the input delimiter. */
138 static char *output_delimiter_string
;
140 /* True if we have ever read standard input. */
141 static bool have_read_stdin
;
143 /* For long options that have no equivalent short option, use a
144 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
147 OUTPUT_DELIMITER_OPTION
= CHAR_MAX
+ 1,
151 static struct option
const longopts
[] =
153 {"bytes", required_argument
, NULL
, 'b'},
154 {"characters", required_argument
, NULL
, 'c'},
155 {"fields", required_argument
, NULL
, 'f'},
156 {"delimiter", required_argument
, NULL
, 'd'},
157 {"only-delimited", no_argument
, NULL
, 's'},
158 {"output-delimiter", required_argument
, NULL
, OUTPUT_DELIMITER_OPTION
},
159 {"complement", no_argument
, NULL
, COMPLEMENT_OPTION
},
160 {GETOPT_HELP_OPTION_DECL
},
161 {GETOPT_VERSION_OPTION_DECL
},
168 if (status
!= EXIT_SUCCESS
)
173 Usage: %s OPTION... [FILE]...\n\
177 Print selected parts of lines from each FILE to standard output.\n\
180 emit_mandatory_arg_note ();
183 -b, --bytes=LIST select only these bytes\n\
184 -c, --characters=LIST select only these characters\n\
185 -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter\n\
188 -f, --fields=LIST select only these fields; also print any line\n\
189 that contains no delimiter character, unless\n\
190 the -s option is specified\n\
194 --complement complement the set of selected bytes, characters\n\
198 -s, --only-delimited do not print lines not containing delimiters\n\
199 --output-delimiter=STRING use STRING as the output delimiter\n\
200 the default is to use the input delimiter\n\
202 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
203 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
206 Use one, and only one of -b, -c or -f. Each LIST is made up of one\n\
207 range, or many ranges separated by commas. Selected input is written\n\
208 in the same order that it is read, and is written exactly once.\n\
211 Each range is one of:\n\
213 N N'th byte, character or field, counted from 1\n\
214 N- from N'th byte, character or field, to end of line\n\
215 N-M from N'th to M'th (included) byte, character or field\n\
216 -M from first to M'th (included) byte, character or field\n\
218 With no FILE, or when FILE is -, read standard input.\n\
220 emit_ancillary_info ();
225 /* Comparison function for qsort to order the list of
226 struct range_pairs. */
228 compare_ranges (const void *a
, const void *b
)
230 int a_start
= ((const struct range_pair
*) a
)->lo
;
231 int b_start
= ((const struct range_pair
*) b
)->lo
;
232 return a_start
< b_start
? -1 : a_start
> b_start
;
235 /* Reallocate Range Pair entries, with corresponding
236 entries outside the range of each specified entry. */
243 struct range_pair
*c
= rp
;
252 add_range_pair (1, c
[0].lo
- 1);
254 for (i
= 1; i
< n
; ++i
)
256 if (c
[i
-1].hi
+ 1 == c
[i
].lo
)
259 add_range_pair (c
[i
-1].hi
+ 1, c
[i
].lo
- 1);
262 if (c
[n
-1].hi
< SIZE_MAX
)
263 add_range_pair (c
[n
-1].hi
+ 1, SIZE_MAX
);
269 /* Given the list of field or byte range specifications FIELDSTR,
270 allocate and initialize the RP array. FIELDSTR should
271 be composed of one or more numbers or ranges of numbers, separated
272 by blanks or commas. Incomplete ranges may be given: '-m' means '1-m';
273 'n-' means 'n' through end of line.
274 Return true if FIELDSTR contains at least one field specification,
278 set_fields (const char *fieldstr
)
280 size_t initial
= 1; /* Value of first number in a range. */
281 size_t value
= 0; /* If nonzero, a number being accumulated. */
282 bool lhs_specified
= false;
283 bool rhs_specified
= false;
284 bool dash_found
= false; /* True if a '-' is found in this field. */
285 bool field_found
= false; /* True if at least one field spec
286 has been processed. */
289 bool in_digits
= false;
291 /* Collect and store in RP the range end points. */
295 if (*fieldstr
== '-')
298 /* Starting a range. */
300 FATAL_ERROR (_("invalid byte, character or field list"));
304 if (lhs_specified
&& !value
)
305 FATAL_ERROR (_("fields and positions are numbered from 1"));
307 initial
= (lhs_specified
? value
: 1);
310 else if (*fieldstr
== ','
311 || isblank (to_uchar (*fieldstr
)) || *fieldstr
== '\0')
314 /* Ending the string, or this field/byte sublist. */
319 if (!lhs_specified
&& !rhs_specified
)
320 FATAL_ERROR (_("invalid range with no endpoint: -"));
322 /* A range. Possibilities: -n, m-n, n-.
323 In any case, 'initial' contains the start of the range. */
326 /* 'n-'. From 'initial' to end of line. */
327 add_range_pair (initial
, SIZE_MAX
);
332 /* 'm-n' or '-n' (1-n). */
334 FATAL_ERROR (_("invalid decreasing range"));
336 add_range_pair (initial
, value
);
343 /* A simple field number, not a range. */
345 FATAL_ERROR (_("fields and positions are numbered from 1"));
346 add_range_pair (value
, value
);
351 if (*fieldstr
== '\0')
355 lhs_specified
= false;
356 rhs_specified
= false;
358 else if (ISDIGIT (*fieldstr
))
360 /* Record beginning of digit string, in case we have to
361 complain about it. */
362 static char const *num_start
;
363 if (!in_digits
|| !num_start
)
364 num_start
= fieldstr
;
372 /* Detect overflow. */
373 if (!DECIMAL_DIGIT_ACCUMULATE (value
, *fieldstr
- '0', size_t)
374 || value
== SIZE_MAX
)
376 /* In case the user specified -c$(echo 2^64|bc),22,
377 complain only about the first number. */
378 /* Determine the length of the offending number. */
379 size_t len
= strspn (num_start
, "0123456789");
380 char *bad_num
= xstrndup (num_start
, len
);
381 if (operating_mode
== byte_mode
)
383 _("byte offset %s is too large"), quote (bad_num
));
386 _("field number %s is too large"), quote (bad_num
));
394 FATAL_ERROR (_("invalid byte, character or field list"));
397 qsort (rp
, n_rp
, sizeof (rp
[0]), compare_ranges
);
399 /* Merge range pairs (e.g. `2-5,3-4' becomes `2-5'). */
400 for (i
= 0; i
< n_rp
; ++i
)
402 for (size_t j
= i
+ 1; j
< n_rp
; ++j
)
404 if (rp
[j
].lo
<= rp
[i
].hi
)
406 rp
[i
].hi
= MAX (rp
[j
].hi
, rp
[i
].hi
);
407 memmove (rp
+ j
, rp
+ j
+ 1, (n_rp
- j
- 1) * sizeof *rp
);
418 /* After merging, reallocate RP so we release memory to the system.
419 Also add a sentinel at the end of RP, to avoid out of bounds access
420 and for perfomance reasons. */
422 rp
= xrealloc (rp
, n_rp
* sizeof (struct range_pair
));
423 rp
[n_rp
- 1].lo
= rp
[n_rp
- 1].hi
= SIZE_MAX
;
428 /* Increment *ITEM_IDX (i.e. a field or byte index),
429 and if required CURRENT_RP. */
432 next_item (size_t *item_idx
)
435 if ((*item_idx
) > current_rp
->hi
)
439 /* Return nonzero if the K'th field or byte is printable. */
444 return current_rp
->lo
<= k
;
447 /* Return nonzero if K'th byte is the beginning of a range. */
450 is_range_start_index (size_t k
)
452 return k
== current_rp
->lo
;
455 /* Read from stream STREAM, printing to standard output any selected bytes. */
458 cut_bytes (FILE *stream
)
460 size_t byte_idx
; /* Number of bytes in the line so far. */
461 /* Whether to begin printing delimiters between ranges for the current line.
462 Set after we've begun printing data corresponding to the first range. */
463 bool print_delimiter
;
466 print_delimiter
= false;
470 int c
; /* Each character from the file. */
478 print_delimiter
= false;
489 next_item (&byte_idx
);
490 if (print_kth (byte_idx
))
492 if (output_delimiter_specified
)
494 if (print_delimiter
&& is_range_start_index (byte_idx
))
496 fwrite (output_delimiter_string
, sizeof (char),
497 output_delimiter_length
, stdout
);
499 print_delimiter
= true;
508 /* Read from stream STREAM, printing to standard output any selected fields. */
511 cut_fields (FILE *stream
)
514 size_t field_idx
= 1;
515 bool found_any_selected_field
= false;
516 bool buffer_first_field
;
527 /* To support the semantics of the -s flag, we may have to buffer
528 all of the first field to determine whether it is 'delimited.'
529 But that is unnecessary if all non-delimited lines must be printed
530 and the first field has been selected, or if non-delimited lines
531 must be suppressed and the first field has *not* been selected.
532 That is because a non-delimited line has exactly one field. */
533 buffer_first_field
= (suppress_non_delimited
^ !print_kth (1));
537 if (field_idx
== 1 && buffer_first_field
)
543 len
= getndelim2 (&field_1_buffer
, &field_1_bufsize
, 0,
544 GETNLINE_NO_LIMIT
, delim
, '\n', stream
);
547 free (field_1_buffer
);
548 field_1_buffer
= NULL
;
549 if (ferror (stream
) || feof (stream
))
555 assert (n_bytes
!= 0);
558 got_line
= field_1_buffer
[n_bytes
- 1] == '\n';
560 /* If the first field extends to the end of line (it is not
561 delimited) and we are printing all non-delimited lines,
563 if (to_uchar (field_1_buffer
[n_bytes
- 1]) != delim
|| got_line
)
565 if (suppress_non_delimited
&& !(got_line
&& delim
== '\n'))
571 fwrite (field_1_buffer
, sizeof (char), n_bytes
, stdout
);
572 /* Make sure the output line is newline terminated. */
581 /* Print the field, but not the trailing delimiter. */
582 fwrite (field_1_buffer
, sizeof (char), n_bytes
- 1, stdout
);
583 found_any_selected_field
= true;
585 next_item (&field_idx
);
590 if (print_kth (field_idx
))
592 if (found_any_selected_field
)
594 fwrite (output_delimiter_string
, sizeof (char),
595 output_delimiter_length
, stdout
);
597 found_any_selected_field
= true;
599 while ((c
= getc (stream
)) != delim
&& c
!= '\n' && c
!= EOF
)
607 while ((c
= getc (stream
)) != delim
&& c
!= '\n' && c
!= EOF
)
613 if (c
== '\n' || c
== EOF
)
615 if (found_any_selected_field
616 || !(suppress_non_delimited
&& field_idx
== 1))
618 if (c
== '\n' || prev_c
!= '\n')
625 found_any_selected_field
= false;
628 next_item (&field_idx
);
633 cut_stream (FILE *stream
)
635 if (operating_mode
== byte_mode
)
641 /* Process file FILE to standard output.
642 Return true if successful. */
645 cut_file (char const *file
)
649 if (STREQ (file
, "-"))
651 have_read_stdin
= true;
656 stream
= fopen (file
, "r");
659 error (0, errno
, "%s", file
);
664 fadvise (stream
, FADVISE_SEQUENTIAL
);
670 error (0, errno
, "%s", file
);
673 if (STREQ (file
, "-"))
674 clearerr (stream
); /* Also clear EOF. */
675 else if (fclose (stream
) == EOF
)
677 error (0, errno
, "%s", file
);
684 main (int argc
, char **argv
)
688 bool delim_specified
= false;
689 char *spec_list_string
IF_LINT ( = NULL
);
691 initialize_main (&argc
, &argv
);
692 set_program_name (argv
[0]);
693 setlocale (LC_ALL
, "");
694 bindtextdomain (PACKAGE
, LOCALEDIR
);
695 textdomain (PACKAGE
);
697 atexit (close_stdout
);
699 operating_mode
= undefined_mode
;
701 /* By default, all non-delimited lines are printed. */
702 suppress_non_delimited
= false;
705 have_read_stdin
= false;
707 while ((optc
= getopt_long (argc
, argv
, "b:c:d:f:ns", longopts
, NULL
)) != -1)
713 /* Build the byte list. */
714 if (operating_mode
!= undefined_mode
)
715 FATAL_ERROR (_("only one type of list may be specified"));
716 operating_mode
= byte_mode
;
717 spec_list_string
= optarg
;
721 /* Build the field list. */
722 if (operating_mode
!= undefined_mode
)
723 FATAL_ERROR (_("only one type of list may be specified"));
724 operating_mode
= field_mode
;
725 spec_list_string
= optarg
;
730 /* Interpret -d '' to mean 'use the NUL byte as the delimiter.' */
731 if (optarg
[0] != '\0' && optarg
[1] != '\0')
732 FATAL_ERROR (_("the delimiter must be a single character"));
734 delim_specified
= true;
737 case OUTPUT_DELIMITER_OPTION
:
738 output_delimiter_specified
= true;
739 /* Interpret --output-delimiter='' to mean
740 'use the NUL byte as the delimiter.' */
741 output_delimiter_length
= (optarg
[0] == '\0'
742 ? 1 : strlen (optarg
));
743 output_delimiter_string
= xstrdup (optarg
);
750 suppress_non_delimited
= true;
753 case COMPLEMENT_OPTION
:
757 case_GETOPT_HELP_CHAR
;
759 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
762 usage (EXIT_FAILURE
);
766 if (operating_mode
== undefined_mode
)
767 FATAL_ERROR (_("you must specify a list of bytes, characters, or fields"));
769 if (delim_specified
&& operating_mode
!= field_mode
)
770 FATAL_ERROR (_("an input delimiter may be specified only\
771 when operating on fields"));
773 if (suppress_non_delimited
&& operating_mode
!= field_mode
)
774 FATAL_ERROR (_("suppressing non-delimited lines makes sense\n\
775 \tonly when operating on fields"));
777 if (! set_fields (spec_list_string
))
779 if (operating_mode
== field_mode
)
780 FATAL_ERROR (_("missing list of fields"));
782 FATAL_ERROR (_("missing list of positions"));
785 if (!delim_specified
)
788 if (output_delimiter_string
== NULL
)
790 static char dummy
[2];
793 output_delimiter_string
= dummy
;
794 output_delimiter_length
= 1;
800 for (ok
= true; optind
< argc
; optind
++)
801 ok
&= cut_file (argv
[optind
]);
804 if (have_read_stdin
&& fclose (stdin
) == EOF
)
806 error (0, errno
, "-");
810 exit (ok
? EXIT_SUCCESS
: EXIT_FAILURE
);