2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002 Tim J. Robbins.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * csplit -- split files based on context
32 * This utility splits its input into numbered output files by line number
33 * or by a regular expression. Regular expression matches have an optional
34 * offset with them, allowing the split to occur a specified number of
35 * lines before or after the match.
37 * To handle negative offsets, we stop reading when the match occurs and
38 * store the offset that the file should have been split at, then use
39 * this output file as input until all the "overflowed" lines have been read.
40 * The file is then closed and truncated to the correct length.
42 * We assume that the output files can be seeked upon (ie. they cannot be
43 * symlinks to named pipes or character devices), but make no such
44 * assumption about the input.
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
50 #include <sys/types.h>
65 static void cleanup(void);
66 static void do_lineno(const char *);
67 static void do_rexp(const char *);
68 static char *get_line(void);
69 static void handlesig(int);
70 static FILE *newfile(void);
71 static void toomuch(FILE *, long);
72 static void usage(void);
75 * Command line options
77 static const char *prefix; /* File name prefix */
78 static long sufflen; /* Number of decimal digits for suffix */
79 static int sflag; /* Suppress output of file names */
80 static int kflag; /* Keep output if error occurs */
83 * Other miscellaneous globals (XXX too many)
85 static long lineno; /* Current line number in input file */
86 static long reps; /* Number of repetitions for this pattern */
87 static long nfiles; /* Number of files output so far */
88 static long maxfiles; /* Maximum number of files we can create */
89 static char currfile[PATH_MAX]; /* Current output file */
90 static const char *infn; /* Name of the input file */
91 static FILE *infile; /* Input file handle */
92 static FILE *overfile; /* Overflow file for toomuch() */
93 static off_t truncofs; /* Offset this file should be truncated at */
94 static int doclean; /* Should cleanup() remove output? */
97 main(int argc, char *argv[])
106 setlocale(LC_ALL, "");
111 while ((ch = getopt(argc, argv, "ksf:n:")) > 0) {
121 sufflen = strtol(optarg, &ep, 10);
122 if (sufflen <= 0 || *ep != '\0' || errno != 0)
123 errx(1, "%s: bad suffix length", optarg);
134 if (sufflen + strlen(prefix) >= PATH_MAX)
135 errx(1, "name too long");
140 if ((infn = *argv++) == NULL)
142 if (strcmp(infn, "-") == 0) {
145 } else if ((infile = fopen(infn, "r")) == NULL)
152 sa.sa_handler = handlesig;
153 sigemptyset(&sa.sa_mask);
154 sigaddset(&sa.sa_mask, SIGHUP);
155 sigaddset(&sa.sa_mask, SIGINT);
156 sigaddset(&sa.sa_mask, SIGTERM);
157 sigaction(SIGHUP, &sa, NULL);
158 sigaction(SIGINT, &sa, NULL);
159 sigaction(SIGTERM, &sa, NULL);
167 /* Ensure 10^sufflen < LONG_MAX. */
168 for (maxfiles = 1, i = 0; i < sufflen; i++) {
169 if (maxfiles > LONG_MAX / 10)
170 errx(1, "%ld: suffix too long (limit %ld)",
175 /* Create files based on supplied patterns. */
176 while (nfiles < maxfiles - 1 && (expr = *argv++) != NULL) {
177 /* Look ahead & see if this pattern has any repetitions. */
178 if (*argv != NULL && **argv == '{') {
180 reps = strtol(*argv + 1, &ep, 10);
181 if (reps < 0 || *ep != '}' || errno != 0)
182 errx(1, "%s: bad repetition count", *argv + 1);
187 if (*expr == '/' || *expr == '%') {
190 while (reps-- != 0 && nfiles < maxfiles - 1);
191 } else if (isdigit((unsigned char)*expr))
194 errx(1, "%s: unrecognised pattern", expr);
197 /* Copy the rest into a new file. */
200 while ((p = get_line()) != NULL && fputs(p, ofp) != EOF)
203 printf("%jd\n", (intmax_t)ftello(ofp));
204 if (fclose(ofp) != 0)
205 err(1, "%s", currfile);
219 "usage: csplit [-ks] [-f prefix] [-n number] file args ...\n");
224 handlesig(int sig __unused)
226 const char msg[] = "csplit: caught signal, cleaning up\n";
228 write(STDERR_FILENO, msg, sizeof(msg) - 1);
233 /* Create a new output file. */
239 if ((size_t)snprintf(currfile, sizeof(currfile), "%s%0*ld", prefix,
240 (int)sufflen, nfiles) >= sizeof(currfile))
241 errc(1, ENAMETOOLONG, NULL);
242 if ((fp = fopen(currfile, "w+")) == NULL)
243 err(1, "%s", currfile);
249 /* Remove partial output, called before exiting. */
253 char fnbuf[PATH_MAX];
260 * NOTE: One cannot portably assume to be able to call snprintf()
261 * from inside a signal handler. It does, however, appear to be safe
262 * to do on FreeBSD. The solution to this problem is worse than the
266 for (i = 0; i < nfiles; i++) {
267 snprintf(fnbuf, sizeof(fnbuf), "%s%0*ld", prefix,
273 /* Read a line from the input into a static buffer. */
277 static char lbuf[LINE_MAX];
280 src = overfile != NULL ? overfile : infile;
282 again: if (fgets(lbuf, sizeof(lbuf), src) == NULL) {
283 if (src == overfile) {
296 /* Conceptually rewind the input (as obtained by get_line()) back `n' lines. */
298 toomuch(FILE *ofp, long n)
303 if (overfile != NULL) {
305 * Truncate the previous file we overflowed into back to
306 * the correct length, close it.
308 if (fflush(overfile) != 0)
310 if (ftruncate(fileno(overfile), truncofs) != 0)
312 if (fclose(overfile) != 0)
318 /* Just tidying up */
324 * Wind the overflow file backwards to `n' lines before the
328 if (ftello(ofp) < (off_t)sizeof(buf))
331 fseeko(ofp, -(off_t)sizeof(buf), SEEK_CUR);
333 errx(1, "%s: can't seek", currfile);
334 if ((nread = fread(buf, 1, sizeof(buf), ofp)) == 0)
335 errx(1, "can't read overflowed output");
336 if (fseeko(ofp, -(off_t)nread, SEEK_CUR) != 0)
337 err(1, "%s", currfile);
338 for (i = 1; i <= nread; i++)
339 if (buf[nread - i] == '\n' && n-- == 0)
341 if (ftello(ofp) == 0)
344 if (fseeko(ofp, nread - i + 1, SEEK_CUR) != 0)
345 err(1, "%s", currfile);
348 * get_line() will read from here. Next call will truncate to
349 * truncofs in this file.
352 truncofs = ftello(overfile);
355 /* Handle splits for /regexp/ and %regexp% patterns. */
357 do_rexp(const char *expr)
363 char *ecopy, *ep, *p, *pofs, *re;
366 if ((ecopy = strdup(expr)) == NULL)
370 if ((pofs = strrchr(ecopy, *expr)) == NULL || pofs[-1] == '\\')
371 errx(1, "%s: missing trailing %c", expr, *expr);
376 ofs = strtol(pofs, &ep, 10);
377 if (*ep != '\0' || errno != 0)
378 errx(1, "%s: bad offset", pofs);
382 if (regcomp(&cre, re, REG_BASIC|REG_NOSUB) != 0)
383 errx(1, "%s: bad regular expression", re);
386 /* /regexp/: Save results to a file. */
389 /* %regexp%: Make a temporary file for overflow. */
390 if ((ofp = tmpfile()) == NULL)
394 /* Read and output lines until we get a match. */
396 while ((p = get_line()) != NULL) {
397 if (fputs(p, ofp) == EOF)
399 if (!first && regexec(&cre, p, 0, NULL, 0) == 0)
406 errx(1, "%s: no match", re);
411 * Negative (or zero) offset: throw back any lines we should
415 toomuch(ofp, -ofs + 1);
416 nwritten = (intmax_t)truncofs;
418 nwritten = (intmax_t)ftello(ofp);
421 * Positive offset: copy the requested number of lines
424 while (--ofs > 0 && (p = get_line()) != NULL)
427 nwritten = (intmax_t)ftello(ofp);
428 if (fclose(ofp) != 0)
429 err(1, "%s", currfile);
432 if (!sflag && *expr == '/')
433 printf("%jd\n", nwritten);
439 /* Handle splits based on line number. */
441 do_lineno(const char *expr)
443 long lastline, tgtline;
448 tgtline = strtol(expr, &ep, 10);
449 if (tgtline <= 0 || errno != 0 || *ep != '\0')
450 errx(1, "%s: bad line number", expr);
452 if (lastline <= lineno)
453 errx(1, "%s: can't go backwards", expr);
455 while (nfiles < maxfiles - 1) {
457 while (lineno + 1 != lastline) {
458 if ((p = get_line()) == NULL)
459 errx(1, "%ld: out of range", lastline);
460 if (fputs(p, ofp) == EOF)
464 printf("%jd\n", (intmax_t)ftello(ofp));
465 if (fclose(ofp) != 0)
466 err(1, "%s", currfile);