1 /* csplit - split a file into sections determined by context lines
2 Copyright (C) 1991-2024 Free Software Foundation, Inc.
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 3 of the License, or
7 (at your option) 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, see <https://www.gnu.org/licenses/>. */
17 /* Written by Stuart Kemp, cpsrk@groper.jcu.edu.au.
18 Modified by David MacKenzie, djm@gnu.ai.mit.edu. */
24 #include <sys/types.h>
31 #include "fd-reopen.h"
33 #include "safe-read.h"
35 #include "xdectoint.h"
38 /* The official name of this program (e.g., no 'g' prefix). */
39 #define PROGRAM_NAME "csplit"
42 proper_name ("Stuart Kemp"), \
43 proper_name ("David MacKenzie")
45 /* The default prefix for output file names. */
46 #define DEFAULT_PREFIX "xx"
48 /* A compiled pattern arg. */
51 intmax_t offset
; /* Offset from regexp to split at. */
52 intmax_t lines_required
; /* Number of lines required. */
53 intmax_t repeat
; /* Repeat count. */
54 int argnum
; /* ARGV index. */
55 bool repeat_forever
; /* True if '*' used as a repeat count. */
56 bool ignore
; /* If true, produce no output (for regexp). */
57 bool regexpr
; /* True if regular expression was used. */
58 struct re_pattern_buffer re_compiled
; /* Compiled regular expression. */
61 /* Initial size of data area in buffers. */
62 #define START_SIZE 8191
64 /* Number of lines kept in each node in line list. */
68 /* Some small values to test the algorithms. */
69 # define START_SIZE 200
73 /* A string with a length count. */
80 /* Pointers to the beginnings of lines in the buffer area.
81 These structures are linked together if needed. */
84 idx_t used
; /* Number of offsets used in this struct. */
85 idx_t insert_index
; /* Next offset to use when inserting line. */
86 idx_t retrieve_index
; /* Next index to use when retrieving line. */
87 struct cstring starts
[CTRL_SIZE
]; /* Lines in the data area. */
88 struct line
*next
; /* Next in linked list. */
91 /* The structure to hold the input lines.
92 Contains a pointer to the data area and a list containing
93 pointers to the individual lines. */
96 idx_t bytes_alloc
; /* Size of the buffer area. */
97 idx_t bytes_used
; /* Bytes used in the buffer area. */
98 intmax_t start_line
; /* First line number in this buffer. */
99 intmax_t first_available
; /* First line that can be retrieved. */
100 idx_t num_lines
; /* Number of complete lines in this buffer. */
101 char *buffer
; /* Data area. */
102 struct line
*line_start
; /* Head of list of pointers to lines. */
103 struct line
*curr_line
; /* The line start record currently in use. */
104 struct buffer_record
*next
;
107 static void close_output_file (void);
108 static void create_output_file (void);
109 static void delete_all_files (bool);
110 static void save_line_to_file (const struct cstring
*line
);
112 /* Start of buffer list. */
113 static struct buffer_record
*head
= nullptr;
115 /* Partially read line. */
116 static char *hold_area
= nullptr;
118 /* Number of bytes in 'hold_area'. */
119 static idx_t hold_count
= 0;
121 /* Number of the last line in the buffers. */
122 static intmax_t last_line_number
= 0;
124 /* Number of the line currently being examined. */
125 static intmax_t current_line
= 0;
127 /* If true, we have read EOF. */
128 static bool have_read_eof
= false;
130 /* Name of output files. */
131 static char *volatile filename_space
= nullptr;
133 /* Prefix part of output file names. */
134 static char const *volatile prefix
= nullptr;
136 /* Suffix part of output file names. */
137 static char *volatile suffix
= nullptr;
139 /* Number of digits to use in output file names. */
140 static int volatile digits
= 2;
142 /* Number of files created so far. */
143 static int volatile files_created
= 0;
145 /* Number of bytes written to current file. */
146 static intmax_t bytes_written
;
148 /* Output file pointer. */
149 static FILE *output_stream
= nullptr;
151 /* Output file name. */
152 static char *output_filename
= nullptr;
154 /* Perhaps it would be cleaner to pass arg values instead of indexes. */
155 static char **global_argv
;
157 /* If true, do not print the count of bytes in each output file. */
158 static bool suppress_count
;
160 /* If true, remove output files on error. */
161 static bool volatile remove_files
;
163 /* If true, remove all output files which have a zero length. */
164 static bool elide_empty_files
;
166 /* If true, suppress the lines that match the PATTERN */
167 static bool suppress_matched
;
169 /* The compiled pattern arguments, which determine how to split
171 static struct control
*controls
;
173 /* Number of elements in 'controls'. */
174 static idx_t control_used
;
176 /* The set of signals that are caught. */
177 static sigset_t caught_signals
;
179 /* For long options that have no equivalent short option, use a
180 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
183 SUPPRESS_MATCHED_OPTION
= CHAR_MAX
+ 1
186 static struct option
const longopts
[] =
188 {"digits", required_argument
, nullptr, 'n'},
189 {"quiet", no_argument
, nullptr, 'q'},
190 {"silent", no_argument
, nullptr, 's'},
191 {"keep-files", no_argument
, nullptr, 'k'},
192 {"elide-empty-files", no_argument
, nullptr, 'z'},
193 {"prefix", required_argument
, nullptr, 'f'},
194 {"suffix-format", required_argument
, nullptr, 'b'},
195 {"suppress-matched", no_argument
, nullptr, SUPPRESS_MATCHED_OPTION
},
196 {GETOPT_HELP_OPTION_DECL
},
197 {GETOPT_VERSION_OPTION_DECL
},
198 {nullptr, 0, nullptr, 0}
201 /* Optionally remove files created so far; then exit.
202 Called when an error detected. */
209 close_output_file ();
211 sigprocmask (SIG_BLOCK
, &caught_signals
, &oldset
);
212 delete_all_files (false);
213 sigprocmask (SIG_SETMASK
, &oldset
, nullptr);
216 static _Noreturn
void
226 error (0, 0, "%s", _("memory exhausted"));
231 interrupt_handler (int sig
)
233 delete_all_files (true);
234 signal (sig
, SIG_DFL
);
235 /* The signal has been reset to SIG_DFL, but blocked during this
236 handler. Force the default action of this signal once the
237 handler returns and the block is removed. */
241 /* Keep track of NUM bytes of a partial line in buffer START.
242 These bytes will be retrieved later when another large buffer is read. */
245 save_to_hold_area (char *start
, idx_t num
)
252 /* Read up to MAX_N_BYTES bytes from the input stream into DEST.
253 Return the number of bytes read. */
256 read_input (char *dest
, idx_t max_n_bytes
)
260 if (max_n_bytes
== 0)
263 bytes_read
= safe_read (STDIN_FILENO
, dest
, max_n_bytes
);
266 have_read_eof
= true;
268 if (bytes_read
== SAFE_READ_ERROR
)
270 error (0, errno
, _("read error"));
277 /* Initialize existing line record P. */
280 clear_line_control (struct line
*p
)
284 p
->retrieve_index
= 0;
287 /* Return a new, initialized line record. */
290 new_line_control (void)
292 struct line
*p
= xmalloc (sizeof *p
);
295 clear_line_control (p
);
300 /* Record LINE_START, which is the address of the start of a line
301 of length LINE_LEN in the large buffer, in the lines buffer of B. */
304 keep_new_line (struct buffer_record
*b
, char *line_start
, idx_t line_len
)
308 /* If there is no existing area to keep line info, get some. */
309 if (b
->line_start
== nullptr)
310 b
->line_start
= b
->curr_line
= new_line_control ();
312 /* If existing area for lines is full, get more. */
313 if (b
->curr_line
->used
== CTRL_SIZE
)
315 b
->curr_line
->next
= new_line_control ();
316 b
->curr_line
= b
->curr_line
->next
;
321 /* Record the start of the line, and update counters. */
322 l
->starts
[l
->insert_index
].str
= line_start
;
323 l
->starts
[l
->insert_index
].len
= line_len
;
328 /* Scan the buffer in B for newline characters
329 and record the line start locations and lengths in B.
330 Return the number of lines found in this buffer.
332 There may be an incomplete line at the end of the buffer;
333 a pointer is kept to this area, which will be used when
334 the next buffer is filled. */
337 record_line_starts (struct buffer_record
*b
)
339 char *line_start
; /* Start of current line. */
340 idx_t lines
; /* Number of lines found. */
341 idx_t line_length
; /* Length of each line found. */
343 if (b
->bytes_used
== 0)
347 line_start
= b
->buffer
;
348 char *buffer_end
= line_start
+ b
->bytes_used
;
353 char *line_end
= rawmemchr (line_start
, '\n');
354 if (line_end
== buffer_end
)
356 line_length
= line_end
- line_start
+ 1;
357 keep_new_line (b
, line_start
, line_length
);
358 line_start
= line_end
+ 1;
362 /* Check for an incomplete last line. */
363 idx_t bytes_left
= buffer_end
- line_start
;
368 keep_new_line (b
, line_start
, bytes_left
);
372 save_to_hold_area (ximemdup (line_start
, bytes_left
), bytes_left
);
375 b
->num_lines
= lines
;
376 b
->first_available
= b
->start_line
= last_line_number
+ 1;
377 last_line_number
+= lines
;
382 /* Work around <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109614>. */
384 # pragma GCC diagnostic ignored "-Wanalyzer-mismatching-deallocation"
385 # pragma GCC diagnostic ignored "-Wanalyzer-use-after-free"
386 # pragma GCC diagnostic ignored "-Wanalyzer-use-of-uninitialized-value"
390 free_buffer (struct buffer_record
*buf
)
392 for (struct line
*l
= buf
->line_start
; l
;)
394 struct line
*n
= l
->next
;
402 /* Return a new buffer of at least MINSIZE bytes. */
404 static ATTRIBUTE_DEALLOC (free_buffer
, 1)
405 struct buffer_record
*
406 get_new_buffer (idx_t min_size
)
408 struct buffer_record
*new_buffer
= xmalloc (sizeof *new_buffer
);
409 new_buffer
->bytes_alloc
= 0;
410 new_buffer
->buffer
= xpalloc (nullptr, &new_buffer
->bytes_alloc
, min_size
,
412 new_buffer
->bytes_used
= 0;
413 new_buffer
->start_line
= new_buffer
->first_available
= last_line_number
+ 1;
414 new_buffer
->num_lines
= 0;
415 new_buffer
->line_start
= new_buffer
->curr_line
= nullptr;
416 new_buffer
->next
= nullptr;
421 /* Append buffer BUF to the linked list of buffers that contain
422 some data yet to be processed. */
425 save_buffer (struct buffer_record
*buf
)
427 struct buffer_record
*p
;
430 buf
->curr_line
= buf
->line_start
;
436 for (p
= head
; p
->next
; p
= p
->next
)
442 /* Fill a buffer of input.
444 Set the initial size of the buffer to a default.
445 Fill the buffer (from the hold area and input stream)
446 and find the individual lines.
447 If no lines are found (the buffer is too small to hold the next line),
448 release the current buffer (whose contents would have been put in the
449 hold area) and repeat the process with another large buffer until at least
450 one entire line has been read.
452 Return true if a new buffer was obtained, otherwise false
453 (in which case end-of-file must have been encountered). */
461 /* We must make the buffer at least as large as the amount of data
462 in the partial line left over from the last call,
463 plus room for a sentinel '\n'. */
464 idx_t bytes_wanted
= MAX (START_SIZE
, hold_count
+ 1);
468 struct buffer_record
*b
= get_new_buffer (bytes_wanted
);
469 idx_t bytes_alloc
= b
->bytes_alloc
;
470 idx_t bytes_avail
= bytes_alloc
;
473 /* First check the 'holding' area for a partial line. */
476 p
= mempcpy (p
, hold_area
, hold_count
);
477 b
->bytes_used
+= hold_count
;
478 bytes_avail
-= hold_count
;
482 b
->bytes_used
+= read_input (p
, bytes_avail
- 1);
484 if (record_line_starts (b
) != 0)
493 if (ckd_add (&bytes_wanted
, bytes_alloc
, bytes_alloc
>> 1))
498 /* Return the line number of the first line that has not yet been retrieved. */
501 get_first_line_in_buffer (void)
503 if (head
== nullptr && !load_buffer ())
504 error (EXIT_FAILURE
, errno
, _("input disappeared"));
506 return head
->first_available
;
509 /* Return a pointer to the logical first line in the buffer and make the
510 next line the logical first line.
511 Return nullptr if there is no more input. */
513 static struct cstring
*
516 /* If non-null, this is the buffer for which the previous call
517 returned the final line. So now, presuming that line has been
518 processed, we can free the buffer and reset this pointer. */
519 static struct buffer_record
*prev_buf
= nullptr;
521 struct cstring
*line
; /* Return value. */
522 struct line
*l
; /* For convenience. */
526 free_buffer (prev_buf
);
530 if (head
== nullptr && !load_buffer ())
533 if (current_line
< head
->first_available
)
534 current_line
= head
->first_available
;
536 ++(head
->first_available
);
540 line
= &l
->starts
[l
->retrieve_index
];
542 /* Advance index to next line. */
543 if (++l
->retrieve_index
== l
->used
)
545 /* Go on to the next line record. */
546 head
->curr_line
= l
->next
;
547 if (head
->curr_line
== nullptr || head
->curr_line
->used
== 0)
549 /* Go on to the next data block.
550 but first record the current one so we can free it
551 once the line we're returning has been processed. */
560 /* Search the buffers for line LINENUM, reading more input if necessary.
561 Return a pointer to the line, or nullptr if it is not found in the file. */
563 static struct cstring
*
564 find_line (intmax_t linenum
)
566 struct buffer_record
*b
;
568 if (head
== nullptr && !load_buffer ())
571 if (linenum
< head
->start_line
)
576 if (linenum
< b
->start_line
+ b
->num_lines
)
578 /* The line is in this buffer. */
580 idx_t offset
; /* How far into the buffer the line is. */
583 offset
= linenum
- b
->start_line
;
584 /* Find the control record. */
585 while (offset
>= CTRL_SIZE
)
590 return &l
->starts
[offset
];
592 if (b
->next
== nullptr && !load_buffer ())
594 b
= b
->next
; /* Try the next data block. */
598 /* Return true if at least one more line is available for input. */
603 return find_line (current_line
+ 1) == nullptr;
606 /* Open NAME as standard input. */
609 set_input_file (char const *name
)
611 if (! STREQ (name
, "-") && fd_reopen (STDIN_FILENO
, name
, O_RDONLY
, 0) < 0)
612 error (EXIT_FAILURE
, errno
, _("cannot open %s for reading"),
616 /* Write all lines from the beginning of the buffer up to, but
617 not including, line LAST_LINE, to the current output file.
618 If IGNORE is true, do not output lines selected here.
619 ARGNUM is the index in ARGV of the current pattern. */
622 write_to_file (intmax_t last_line
, bool ignore
, int argnum
)
624 struct cstring
*line
;
625 intmax_t first_line
; /* First available input line. */
626 intmax_t lines
; /* Number of lines to output. */
629 first_line
= get_first_line_in_buffer ();
631 if (first_line
> last_line
)
633 error (0, 0, _("%s: line number out of range"),
634 quote (global_argv
[argnum
]));
638 lines
= last_line
- first_line
;
640 for (i
= 0; i
< lines
; i
++)
642 line
= remove_line ();
645 error (0, 0, _("%s: line number out of range"),
646 quote (global_argv
[argnum
]));
650 save_line_to_file (line
);
654 /* Output any lines left after all regexps have been processed. */
657 dump_rest_of_file (void)
659 struct cstring
*line
;
661 while ((line
= remove_line ()) != nullptr)
662 save_line_to_file (line
);
665 /* Handle an attempt to read beyond EOF under the control of record P,
666 on iteration REPETITION if nonzero. */
669 handle_line_error (const struct control
*p
, intmax_t repetition
)
671 char buf
[INT_BUFSIZE_BOUND (intmax_t)];
673 fprintf (stderr
, _("%s: %s: line number out of range"),
674 program_name
, quote (imaxtostr (p
->lines_required
, buf
)));
676 fprintf (stderr
, _(" on repetition %s\n"), imaxtostr (repetition
, buf
));
678 fprintf (stderr
, "\n");
683 /* Determine the line number that marks the end of this file,
684 then get those lines and save them to the output file.
685 P is the control record.
686 REPETITION is the repetition number. */
689 process_line_count (const struct control
*p
, intmax_t repetition
)
692 intmax_t last_line_to_save
= p
->lines_required
* (repetition
+ 1);
694 create_output_file ();
696 /* Ensure that the line number specified is not 1 greater than
697 the number of lines in the file.
698 When suppressing matched lines, check before the loop. */
699 if (no_more_lines () && suppress_matched
)
700 handle_line_error (p
, repetition
);
702 linenum
= get_first_line_in_buffer ();
703 while (linenum
++ < last_line_to_save
)
705 struct cstring
*line
= remove_line ();
707 handle_line_error (p
, repetition
);
708 save_line_to_file (line
);
711 close_output_file ();
713 if (suppress_matched
)
716 /* Ensure that the line number specified is not 1 greater than
717 the number of lines in the file. */
718 if (no_more_lines () && !suppress_matched
)
719 handle_line_error (p
, repetition
);
723 regexp_error (struct control
*p
, intmax_t repetition
, bool ignore
)
725 fprintf (stderr
, _("%s: %s: match not found"),
726 program_name
, quote (global_argv
[p
->argnum
]));
730 char buf
[INT_BUFSIZE_BOUND (intmax_t)];
731 fprintf (stderr
, _(" on repetition %s\n"), imaxtostr (repetition
, buf
));
734 fprintf (stderr
, "\n");
738 dump_rest_of_file ();
739 close_output_file ();
744 /* Read the input until a line matches the regexp in P, outputting
745 it unless P->IGNORE is true.
746 REPETITION is this repeat-count; 0 means the first time. */
749 process_regexp (struct control
*p
, intmax_t repetition
)
751 struct cstring
*line
; /* From input file. */
752 idx_t line_len
; /* To make "$" in regexps work. */
753 intmax_t break_line
; /* First line number of next file. */
754 bool ignore
= p
->ignore
; /* If true, skip this section. */
758 create_output_file ();
760 /* If there is no offset for the regular expression, or
761 it is positive, then it is not necessary to buffer the lines. */
767 line
= find_line (++current_line
);
770 if (p
->repeat_forever
)
774 dump_rest_of_file ();
775 close_output_file ();
780 regexp_error (p
, repetition
, ignore
);
782 line_len
= line
->len
;
783 if (line
->str
[line_len
- 1] == '\n')
785 ret
= re_search (&p
->re_compiled
, line
->str
, line_len
,
786 0, line_len
, nullptr);
789 error (0, 0, _("error in regular expression search"));
794 line
= remove_line ();
796 save_line_to_file (line
);
804 /* Buffer the lines. */
807 line
= find_line (++current_line
);
810 if (p
->repeat_forever
)
814 dump_rest_of_file ();
815 close_output_file ();
820 regexp_error (p
, repetition
, ignore
);
822 line_len
= line
->len
;
823 if (line
->str
[line_len
- 1] == '\n')
825 ret
= re_search (&p
->re_compiled
, line
->str
, line_len
,
826 0, line_len
, nullptr);
829 error (0, 0, _("error in regular expression search"));
837 /* Account for any offset from this regexp. */
838 break_line
= current_line
+ p
->offset
;
840 write_to_file (break_line
, ignore
, p
->argnum
);
843 close_output_file ();
846 current_line
= break_line
;
848 if (suppress_matched
)
852 /* Split the input file according to the control records we have built. */
857 for (idx_t i
= 0; i
< control_used
; i
++)
860 if (controls
[i
].regexpr
)
862 for (j
= 0; (controls
[i
].repeat_forever
863 || j
<= controls
[i
].repeat
); j
++)
864 process_regexp (&controls
[i
], j
);
868 for (j
= 0; (controls
[i
].repeat_forever
869 || j
<= controls
[i
].repeat
); j
++)
870 process_line_count (&controls
[i
], j
);
874 create_output_file ();
875 dump_rest_of_file ();
876 close_output_file ();
879 /* Return the name of output file number NUM.
881 This function is called from a signal handler, so it should invoke
882 only reentrant functions that are async-signal-safe. POSIX does
883 not guarantee this for the functions called below, but we don't
884 know of any hosts where this implementation isn't safe. */
887 make_filename (int num
)
889 strcpy (filename_space
, prefix
);
891 sprintf (filename_space
+ strlen (prefix
), suffix
, num
);
893 sprintf (filename_space
+ strlen (prefix
), "%0*d", digits
, num
);
894 return filename_space
;
897 /* Create the next output file. */
900 create_output_file (void)
902 int nfiles
= files_created
;
906 output_filename
= make_filename (nfiles
);
908 if (nfiles
== INT_MAX
)
911 fopen_errno
= EOVERFLOW
;
915 /* Create the output file in a critical section, to avoid races. */
917 sigprocmask (SIG_BLOCK
, &caught_signals
, &oldset
);
918 output_stream
= fopen (output_filename
, "w");
919 fopen_ok
= (output_stream
!= nullptr);
921 files_created
= nfiles
+ fopen_ok
;
922 sigprocmask (SIG_SETMASK
, &oldset
, nullptr);
927 error (0, fopen_errno
, "%s", quotef (output_filename
));
933 /* If requested, delete all the files we have created. This function
934 must be called only from critical sections. */
937 delete_all_files (bool in_signal_handler
)
942 for (int i
= files_created
; 0 <= --i
; )
944 char const *name
= make_filename (i
);
945 if (unlink (name
) != 0 && errno
!= ENOENT
&& !in_signal_handler
)
946 error (0, errno
, "%s", quotef (name
));
952 /* Close the current output file and print the count
953 of characters in this file. */
956 close_output_file (void)
960 if (ferror (output_stream
))
962 error (0, 0, _("write error for %s"), quoteaf (output_filename
));
963 output_stream
= nullptr;
966 if (fclose (output_stream
) != 0)
968 error (0, errno
, "%s", quotef (output_filename
));
969 output_stream
= nullptr;
972 if (bytes_written
== 0 && elide_empty_files
)
978 /* Remove the output file in a critical section, to avoid races. */
979 sigprocmask (SIG_BLOCK
, &caught_signals
, &oldset
);
980 unlink_ok
= (unlink (output_filename
) == 0);
981 unlink_errno
= errno
;
983 sigprocmask (SIG_SETMASK
, &oldset
, nullptr);
985 if (! unlink_ok
&& unlink_errno
!= ENOENT
)
986 error (0, unlink_errno
, "%s", quotef (output_filename
));
992 char buf
[INT_BUFSIZE_BOUND (intmax_t)];
993 fprintf (stdout
, "%s\n", imaxtostr (bytes_written
, buf
));
996 output_stream
= nullptr;
1000 /* Save line LINE to the output file and
1001 increment the character count for the current file. */
1004 save_line_to_file (const struct cstring
*line
)
1006 idx_t l
= fwrite (line
->str
, sizeof (char), line
->len
, output_stream
);
1009 error (0, errno
, _("write error for %s"), quoteaf (output_filename
));
1010 output_stream
= nullptr;
1013 bytes_written
+= line
->len
;
1016 /* Return a new, initialized control record. */
1018 static struct control
*
1019 new_control_record (void)
1021 static idx_t control_allocated
= 0; /* Total space allocated. */
1024 if (control_used
== control_allocated
)
1025 controls
= xpalloc (controls
, &control_allocated
, 1, -1, sizeof *controls
);
1026 p
= &controls
[control_used
++];
1029 p
->repeat_forever
= false;
1030 p
->lines_required
= 0;
1035 /* Check if there is a numeric offset after a regular expression.
1036 STR is the entire command line argument.
1037 P is the control record for this regular expression.
1038 NUM is the numeric part of STR. */
1041 check_for_offset (struct control
*p
, char const *str
, char const *num
)
1043 if (xstrtoimax (num
, nullptr, 10, &p
->offset
, "") != LONGINT_OK
)
1044 error (EXIT_FAILURE
, 0, _("%s: integer expected after delimiter"),
1048 /* Given that the first character of command line arg STR is '{',
1049 make sure that the rest of the string is a valid repeat count
1050 and store its value in P.
1051 ARGNUM is the ARGV index of STR. */
1054 parse_repeat_count (int argnum
, struct control
*p
, char *str
)
1058 end
= str
+ strlen (str
) - 1;
1060 error (EXIT_FAILURE
, 0, _("%s: '}' is required in repeat count"),
1064 if (str
+ 1 == end
- 1 && *(str
+ 1) == '*')
1065 p
->repeat_forever
= true;
1069 if (xstrtoumax (str
+ 1, nullptr, 10, &val
, "") != LONGINT_OK
1070 || INTMAX_MAX
< val
)
1072 error (EXIT_FAILURE
, 0,
1073 _("%s}: integer required between '{' and '}'"),
1074 quote (global_argv
[argnum
]));
1082 /* Extract the regular expression from STR and check for a numeric offset.
1083 STR should start with the regexp delimiter character.
1084 Return a new control record for the regular expression.
1085 ARGNUM is the ARGV index of STR.
1086 Unless IGNORE is true, mark these lines for output. */
1088 static struct control
*
1089 extract_regexp (int argnum
, bool ignore
, char const *str
)
1091 idx_t len
; /* Number of bytes in this regexp. */
1093 char const *closing_delim
;
1097 closing_delim
= strrchr (str
+ 1, delim
);
1098 if (closing_delim
== nullptr)
1099 error (EXIT_FAILURE
, 0,
1100 _("%s: closing delimiter '%c' missing"), str
, delim
);
1102 len
= closing_delim
- str
- 1;
1103 p
= new_control_record ();
1108 p
->re_compiled
.buffer
= nullptr;
1109 p
->re_compiled
.allocated
= 0;
1110 p
->re_compiled
.fastmap
= xmalloc (UCHAR_MAX
+ 1);
1111 p
->re_compiled
.translate
= nullptr;
1113 RE_SYNTAX_POSIX_BASIC
& ~RE_CONTEXT_INVALID_DUP
& ~RE_NO_EMPTY_RANGES
;
1114 err
= re_compile_pattern (str
+ 1, len
, &p
->re_compiled
);
1117 error (0, 0, _("%s: invalid regular expression: %s"), quote (str
), err
);
1121 if (closing_delim
[1])
1122 check_for_offset (p
, str
, closing_delim
+ 1);
1127 /* Extract the break patterns from args START through ARGC - 1 of ARGV.
1128 After each pattern, check if the next argument is a repeat count. */
1131 parse_patterns (int argc
, int start
, char **argv
)
1133 struct control
*p
; /* New control record created. */
1134 static intmax_t last_val
= 0;
1136 for (int i
= start
; i
< argc
; i
++)
1138 if (*argv
[i
] == '/' || *argv
[i
] == '%')
1140 p
= extract_regexp (i
, *argv
[i
] == '%', argv
[i
]);
1144 p
= new_control_record ();
1148 if (xstrtoumax (argv
[i
], nullptr, 10, &val
, "") != LONGINT_OK
1149 || INTMAX_MAX
< val
)
1150 error (EXIT_FAILURE
, 0, _("%s: invalid pattern"), quote (argv
[i
]));
1152 error (EXIT_FAILURE
, 0,
1153 _("%s: line number must be greater than zero"), argv
[i
]);
1156 char buf
[INT_BUFSIZE_BOUND (intmax_t)];
1157 error (EXIT_FAILURE
, 0,
1158 _("line number %s is smaller than preceding line number,"
1160 quote (argv
[i
]), imaxtostr (last_val
, buf
));
1163 if (val
== last_val
)
1165 _("warning: line number %s is the same as preceding line number"),
1170 p
->lines_required
= val
;
1173 if (i
+ 1 < argc
&& *argv
[i
+ 1] == '{')
1175 /* We have a repeat count. */
1177 parse_repeat_count (i
, p
, argv
[i
]);
1184 /* Names for the printf format flags ' and #. These can be ORed together. */
1185 enum { FLAG_THOUSANDS
= 1, FLAG_ALTERNATIVE
= 2 };
1187 /* Scan the printf format flags in FORMAT, storing info about the
1188 flags into *FLAGS_PTR. Return the number of flags found. */
1190 get_format_flags (char const *format
, int *flags_ptr
)
1194 for (idx_t count
= 0; ; count
++)
1196 switch (format
[count
])
1203 flags
|= FLAG_THOUSANDS
;
1207 flags
|= FLAG_ALTERNATIVE
;
1217 /* Check that the printf format conversion specifier *FORMAT is valid
1218 and compatible with FLAGS. Change it to 'd' if it is 'u',
1219 since the format will be used with a signed value. */
1221 check_format_conv_type (char *format
, int flags
)
1223 unsigned char ch
= *format
;
1224 int compatible_flags
= FLAG_THOUSANDS
;
1239 compatible_flags
= FLAG_ALTERNATIVE
;
1243 error (EXIT_FAILURE
, 0, _("missing conversion specifier in suffix"));
1247 error (EXIT_FAILURE
, 0,
1248 _("invalid conversion specifier in suffix: %c"), ch
);
1250 error (EXIT_FAILURE
, 0,
1251 _("invalid conversion specifier in suffix: \\%.3o"), ch
);
1254 if (flags
& ~ compatible_flags
)
1255 error (EXIT_FAILURE
, 0,
1256 _("invalid flags in conversion specification: %%%c%c"),
1257 (flags
& ~ compatible_flags
& FLAG_ALTERNATIVE
? '#' : '\''), ch
);
1260 /* Return the maximum number of bytes that can be generated by
1261 applying FORMAT to an int value. If the format is
1262 invalid, diagnose the problem and exit. */
1264 max_out (char *format
)
1266 bool percent
= false;
1268 for (char *f
= format
; *f
; f
++)
1269 if (*f
== '%' && *++f
!= '%')
1272 error (EXIT_FAILURE
, 0,
1273 _("too many %% conversion specifications in suffix"));
1276 f
+= get_format_flags (f
, &flags
);
1277 while (ISDIGIT (*f
))
1280 while (ISDIGIT (*++f
))
1282 check_format_conv_type (f
, flags
);
1286 error (EXIT_FAILURE
, 0,
1287 _("missing %% conversion specification in suffix"));
1289 int maxlen
= snprintf (nullptr, 0, format
, INT_MAX
);
1296 main (int argc
, char **argv
)
1300 initialize_main (&argc
, &argv
);
1301 set_program_name (argv
[0]);
1302 setlocale (LC_ALL
, "");
1303 bindtextdomain (PACKAGE
, LOCALEDIR
);
1304 textdomain (PACKAGE
);
1306 atexit (close_stdout
);
1311 suppress_count
= false;
1312 remove_files
= true;
1313 suppress_matched
= false;
1314 prefix
= DEFAULT_PREFIX
;
1316 while ((optc
= getopt_long (argc
, argv
, "f:b:kn:sqz", longopts
, nullptr))
1329 remove_files
= false;
1333 digits
= xdectoimax (optarg
, 0, MIN (INT_MAX
, IDX_MAX
), "",
1334 _("invalid number"), 0);
1339 suppress_count
= true;
1343 elide_empty_files
= true;
1346 case SUPPRESS_MATCHED_OPTION
:
1347 suppress_matched
= true;
1350 case_GETOPT_HELP_CHAR
;
1352 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1355 usage (EXIT_FAILURE
);
1358 if (argc
- optind
< 2)
1361 error (0, 0, _("missing operand"));
1363 error (0, 0, _("missing operand after %s"), quote (argv
[argc
- 1]));
1364 usage (EXIT_FAILURE
);
1367 idx_t prefix_len
= strlen (prefix
);
1368 idx_t max_digit_string_len
1371 : MAX (INT_STRLEN_BOUND (int), digits
));
1372 idx_t filename_size
;
1373 if (ckd_add (&filename_size
, prefix_len
, max_digit_string_len
+ 1))
1375 filename_space
= ximalloc (filename_size
);
1377 set_input_file (argv
[optind
++]);
1379 parse_patterns (argc
, optind
, argv
);
1383 static int const sig
[] =
1385 /* The usual suspects. */
1386 SIGALRM
, SIGHUP
, SIGINT
, SIGPIPE
, SIGQUIT
, SIGTERM
,
1403 enum { nsigs
= ARRAY_CARDINALITY (sig
) };
1405 struct sigaction act
;
1407 sigemptyset (&caught_signals
);
1408 for (i
= 0; i
< nsigs
; i
++)
1410 sigaction (sig
[i
], nullptr, &act
);
1411 if (act
.sa_handler
!= SIG_IGN
)
1412 sigaddset (&caught_signals
, sig
[i
]);
1415 act
.sa_handler
= interrupt_handler
;
1416 act
.sa_mask
= caught_signals
;
1419 for (i
= 0; i
< nsigs
; i
++)
1420 if (sigismember (&caught_signals
, sig
[i
]))
1421 sigaction (sig
[i
], &act
, nullptr);
1426 if (close (STDIN_FILENO
) != 0)
1428 error (0, errno
, _("read error"));
1432 return EXIT_SUCCESS
;
1438 if (status
!= EXIT_SUCCESS
)
1443 Usage: %s [OPTION]... FILE PATTERN...\n\
1447 Output pieces of FILE separated by PATTERN(s) to files 'xx00', 'xx01', ...,\n\
1448 and output byte counts of each piece to standard output.\n\
1452 Read standard input if FILE is -\n\
1455 emit_mandatory_arg_note ();
1458 -b, --suffix-format=FORMAT use sprintf FORMAT instead of %02d\n\
1459 -f, --prefix=PREFIX use PREFIX instead of 'xx'\n\
1460 -k, --keep-files do not remove output files on errors\n\
1463 --suppress-matched suppress the lines matching PATTERN\n\
1466 -n, --digits=DIGITS use specified number of digits instead of 2\n\
1467 -s, --quiet, --silent do not print counts of output file sizes\n\
1468 -z, --elide-empty-files suppress empty output files\n\
1470 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
1471 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
1474 Each PATTERN may be:\n\
1475 INTEGER copy up to but not including specified line number\n\
1476 /REGEXP/[OFFSET] copy up to but not including a matching line\n\
1477 %REGEXP%[OFFSET] skip to, but not including a matching line\n\
1478 {INTEGER} repeat the previous pattern specified number of times\n\
1479 {*} repeat the previous pattern as many times as possible\n\
1481 A line OFFSET is an integer optionally preceded by '+' or '-'\n\
1483 emit_ancillary_info (PROGRAM_NAME
);