2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1987, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
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.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #include <sys/param.h>
52 #define DEFLINE 1000 /* Default num lines per file. */
54 static off_t bytecnt; /* Byte count to split on. */
55 static long chunks; /* Chunks count to split into. */
56 static bool clobber = true; /* Whether to overwrite existing output files. */
57 static long numlines; /* Line count to split on. */
58 static int file_open; /* If a file open. */
59 static int ifd = -1, ofd = -1; /* Input/output file descriptors. */
60 static char fname[MAXPATHLEN]; /* File name prefix. */
64 static long sufflen = 2; /* File name suffix length. */
65 static bool autosfx = true; /* Whether to auto-extend the suffix length. */
67 static void newfile(void);
68 static void split1(void);
69 static void split2(void);
70 static void split3(void);
71 static void usage(void) __dead2;
74 main(int argc, char **argv)
77 const char *p, *errstr;
80 setlocale(LC_ALL, "");
83 while ((ch = getopt(argc, argv, "0::1::2::3::4::5::6::7::8::9::a:b:cdl:n:p:")) != -1)
85 case '0': case '1': case '2': case '3': case '4':
86 case '5': case '6': case '7': case '8': case '9':
88 * Undocumented kludge: split was originally designed
89 * to take a number after a dash.
94 p = optarg ? optarg : "";
95 while (numlines >= 0 && *p >= '0' && *p <= '9')
96 numlines = numlines * 10 + *p++ - '0';
97 if (numlines <= 0 || *p != '\0')
98 errx(EX_USAGE, "%c%s: line count is invalid",
99 ch, optarg ? optarg : "");
101 case 'a': /* Suffix length */
102 sufflen = strtonum(optarg, 0, INT_MAX, &errstr);
103 if (errstr != NULL) {
104 errx(EX_USAGE, "%s: suffix length is %s",
114 case 'b': /* Byte count. */
115 if (expand_number(optarg, &bytecnt) != 0) {
116 errx(EX_USAGE, "%s: byte count is invalid",
120 case 'c': /* Continue, don't overwrite output files. */
123 case 'd': /* Decimal suffix */
126 case 'l': /* Line count. */
129 numlines = strtonum(optarg, 1, LONG_MAX, &errstr);
130 if (errstr != NULL) {
131 errx(EX_USAGE, "%s: line count is %s",
135 case 'n': /* Chunks. */
136 chunks = strtonum(optarg, 1, LONG_MAX, &errstr);
137 if (errstr != NULL) {
138 errx(EX_USAGE, "%s: number of chunks is %s",
143 case 'p': /* pattern matching. */
144 error = regcomp(&rgx, optarg, REG_EXTENDED|REG_NOSUB);
146 regerror(error, &rgx, errbuf, sizeof(errbuf));
147 errx(EX_USAGE, "%s: regex is invalid: %s",
158 if (argc > 0) { /* Input file. */
159 if (strcmp(*argv, "-") == 0)
161 else if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
162 err(EX_NOINPUT, "%s", *argv);
166 if (argc > 0) { /* File name prefix. */
167 if (strlcpy(fname, *argv, sizeof(fname)) >= sizeof(fname)) {
168 errx(EX_USAGE, "%s: file name prefix is too long",
177 if (strlen(fname) + (unsigned long)sufflen >= sizeof(fname))
178 errx(EX_USAGE, "suffix is too long");
179 if (pflag && (numlines != 0 || bytecnt != 0 || chunks != 0))
184 else if (bytecnt != 0 || chunks != 0)
187 if (bytecnt != 0 && chunks != 0)
190 if (ifd == -1) /* Stdin by default. */
196 } else if (chunks != 0) {
208 * Split the input by bytes.
213 static char bfr[MAXBSIZE];
222 switch ((len = read(ifd, bfr, sizeof(bfr)))) {
226 err(EX_IOERR, "read");
230 if (chunks == 0 || nfiles < chunks) {
235 if (bcnt + len >= bytecnt) {
236 dist = bytecnt - bcnt;
237 if (write(ofd, bfr, dist) != dist)
238 err(EX_IOERR, "write");
240 for (C = bfr + dist; len >= bytecnt;
241 len -= bytecnt, C += bytecnt) {
242 if (chunks == 0 || nfiles < chunks) {
246 if (write(ofd, C, bytecnt) != bytecnt)
247 err(EX_IOERR, "write");
250 if (chunks == 0 || nfiles < chunks) {
254 if (write(ofd, C, len) != len)
255 err(EX_IOERR, "write");
262 if (write(ofd, bfr, len) != len)
263 err(EX_IOERR, "write");
270 * Split the input by lines.
284 /* Stick a stream on top of input file descriptor */
285 if ((infp = fdopen(ifd, "r")) == NULL)
286 err(EX_NOINPUT, "fdopen");
288 /* Process input one line at a time */
289 while ((errno = 0, len = getline(&buf, &bufsize, infp)) > 0) {
290 /* Check if we need to start a new file */
295 pmatch.rm_eo = len - 1;
296 if (regexec(&rgx, buf, 0, &pmatch, REG_STARTEND) == 0)
298 } else if (lcnt++ == numlines) {
303 /* Open output file if needed */
308 if (write(ofd, buf, len) != len)
309 err(EX_IOERR, "write");
313 if ((len == -1 && errno != 0) || ferror(infp))
314 err(EX_IOERR, "read");
321 * Split the input into specified number of chunks
328 if (fstat(ifd, &sb) == -1) {
333 if (chunks > sb.st_size) {
334 errx(1, "can't split into more than %d files",
339 bytecnt = sb.st_size / chunks;
346 * Open a new output file.
351 long i, maxfiles, tfnum;
356 int flags = O_WRONLY | O_CREAT | O_TRUNC;
362 if (fname[0] == '\0') {
366 fpnt = fname + strlen(fname);
368 } else if (close(ofd) != 0)
380 pattlen = end - beg + 1;
383 * If '-a' is not specified, then we automatically expand the
384 * suffix length to accomodate splitting all input. We do this
385 * by moving the suffix pointer (fpnt) forward and incrementing
386 * sufflen by one, thereby yielding an additional two characters
387 * and allowing all output files to sort such that 'cat *' yields
388 * the input in order. I.e., the order is '... xyy xyz xzaaa
389 * xzaab ... xzyzy, xzyzz, xzzaaaa, xzzaaab' and so on.
391 if (!dflag && autosfx && (fpnt[0] == 'y') &&
392 strspn(fpnt+1, "z") == strlen(fpnt+1)) {
393 fpnt = fname + strlen(fname) - sufflen;
394 fpnt[sufflen + 2] = '\0';
406 /* Reset so we start back at all 'a's in our extended suffix. */
410 /* maxfiles = pattlen^sufflen, but don't use libm. */
411 for (maxfiles = 1, i = 0; i < sufflen; i++)
412 if (LONG_MAX / pattlen < maxfiles)
413 errx(EX_USAGE, "suffix is too long (max %ld)", i);
417 if (fnum == maxfiles)
418 errx(EX_DATAERR, "too many files");
420 /* Generate suffix of sufflen letters */
424 fpnt[i] = tfnum % pattlen + beg;
427 fpnt[sufflen] = '\0';
430 if ((ofd = open(fname, flags, DEFFILEMODE)) < 0) {
431 if (!clobber && errno == EEXIST)
433 err(EX_IOERR, "%s", fname);
441 (void)fprintf(stderr,
442 "usage: split [-cd] [-l line_count] [-a suffix_length] [file [prefix]]\n"
443 " split [-cd] -b byte_count[K|k|M|m|G|g] [-a suffix_length] [file [prefix]]\n"
444 " split [-cd] -n chunk_count [-a suffix_length] [file [prefix]]\n"
445 " split [-cd] -p pattern [-a suffix_length] [file [prefix]]\n");