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/cdefs.h>
34 static const char copyright[] =
35 "@(#) Copyright (c) 1987, 1993, 1994\n\
36 The Regents of the University of California. All rights reserved.\n";
40 static const char sccsid[] = "@(#)split.c 8.2 (Berkeley) 4/16/94";
43 #include <sys/param.h>
63 #define DEFLINE 1000 /* Default num lines per file. */
65 static off_t bytecnt; /* Byte count to split on. */
66 static long chunks; /* Chunks count to split into. */
67 static bool clobber = true; /* Whether to overwrite existing output files. */
68 static long numlines; /* Line count to split on. */
69 static int file_open; /* If a file open. */
70 static int ifd = -1, ofd = -1; /* Input/output file descriptors. */
71 static char fname[MAXPATHLEN]; /* File name prefix. */
75 static long sufflen = 2; /* File name suffix length. */
76 static bool autosfx = true; /* Whether to auto-extend the suffix length. */
78 static void newfile(void);
79 static void split1(void);
80 static void split2(void);
81 static void split3(void);
82 static void usage(void) __dead2;
85 main(int argc, char **argv)
88 const char *p, *errstr;
91 setlocale(LC_ALL, "");
94 while ((ch = getopt(argc, argv, "0::1::2::3::4::5::6::7::8::9::a:b:cdl:n:p:")) != -1)
96 case '0': case '1': case '2': case '3': case '4':
97 case '5': case '6': case '7': case '8': case '9':
99 * Undocumented kludge: split was originally designed
100 * to take a number after a dash.
105 p = optarg ? optarg : "";
106 while (numlines >= 0 && *p >= '0' && *p <= '9')
107 numlines = numlines * 10 + *p++ - '0';
108 if (numlines <= 0 || *p != '\0')
109 errx(EX_USAGE, "%c%s: line count is invalid",
110 ch, optarg ? optarg : "");
112 case 'a': /* Suffix length */
113 sufflen = strtonum(optarg, 0, INT_MAX, &errstr);
114 if (errstr != NULL) {
115 errx(EX_USAGE, "%s: suffix length is %s",
125 case 'b': /* Byte count. */
126 if (expand_number(optarg, &bytecnt) != 0) {
127 errx(EX_USAGE, "%s: byte count is invalid",
131 case 'c': /* Continue, don't overwrite output files. */
134 case 'd': /* Decimal suffix */
137 case 'l': /* Line count. */
140 numlines = strtonum(optarg, 1, LONG_MAX, &errstr);
141 if (errstr != NULL) {
142 errx(EX_USAGE, "%s: line count is %s",
146 case 'n': /* Chunks. */
147 chunks = strtonum(optarg, 1, LONG_MAX, &errstr);
148 if (errstr != NULL) {
149 errx(EX_USAGE, "%s: number of chunks is %s",
154 case 'p': /* pattern matching. */
155 error = regcomp(&rgx, optarg, REG_EXTENDED|REG_NOSUB);
157 regerror(error, &rgx, errbuf, sizeof(errbuf));
158 errx(EX_USAGE, "%s: regex is invalid: %s",
169 if (argc > 0) { /* Input file. */
170 if (strcmp(*argv, "-") == 0)
172 else if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
173 err(EX_NOINPUT, "%s", *argv);
177 if (argc > 0) { /* File name prefix. */
178 if (strlcpy(fname, *argv, sizeof(fname)) >= sizeof(fname)) {
179 errx(EX_USAGE, "%s: file name prefix is too long",
188 if (strlen(fname) + (unsigned long)sufflen >= sizeof(fname))
189 errx(EX_USAGE, "suffix is too long");
190 if (pflag && (numlines != 0 || bytecnt != 0 || chunks != 0))
195 else if (bytecnt != 0 || chunks != 0)
198 if (bytecnt != 0 && chunks != 0)
201 if (ifd == -1) /* Stdin by default. */
207 } else if (chunks != 0) {
219 * Split the input by bytes.
224 static char bfr[MAXBSIZE];
233 switch ((len = read(ifd, bfr, sizeof(bfr)))) {
237 err(EX_IOERR, "read");
241 if (chunks == 0 || nfiles < chunks) {
246 if (bcnt + len >= bytecnt) {
247 dist = bytecnt - bcnt;
248 if (write(ofd, bfr, dist) != dist)
249 err(EX_IOERR, "write");
251 for (C = bfr + dist; len >= bytecnt;
252 len -= bytecnt, C += bytecnt) {
253 if (chunks == 0 || nfiles < chunks) {
257 if (write(ofd, C, bytecnt) != bytecnt)
258 err(EX_IOERR, "write");
261 if (chunks == 0 || nfiles < chunks) {
265 if (write(ofd, C, len) != len)
266 err(EX_IOERR, "write");
273 if (write(ofd, bfr, len) != len)
274 err(EX_IOERR, "write");
281 * Split the input by lines.
295 /* Stick a stream on top of input file descriptor */
296 if ((infp = fdopen(ifd, "r")) == NULL)
297 err(EX_NOINPUT, "fdopen");
299 /* Process input one line at a time */
300 while ((errno = 0, len = getline(&buf, &bufsize, infp)) > 0) {
301 /* Check if we need to start a new file */
306 pmatch.rm_eo = len - 1;
307 if (regexec(&rgx, buf, 0, &pmatch, REG_STARTEND) == 0)
309 } else if (lcnt++ == numlines) {
314 /* Open output file if needed */
319 if (write(ofd, buf, len) != len)
320 err(EX_IOERR, "write");
324 if ((len == -1 && errno != 0) || ferror(infp))
325 err(EX_IOERR, "read");
332 * Split the input into specified number of chunks
339 if (fstat(ifd, &sb) == -1) {
344 if (chunks > sb.st_size) {
345 errx(1, "can't split into more than %d files",
350 bytecnt = sb.st_size / chunks;
357 * Open a new output file.
362 long i, maxfiles, tfnum;
367 int flags = O_WRONLY | O_CREAT | O_TRUNC;
373 if (fname[0] == '\0') {
377 fpnt = fname + strlen(fname);
379 } else if (close(ofd) != 0)
391 pattlen = end - beg + 1;
394 * If '-a' is not specified, then we automatically expand the
395 * suffix length to accomodate splitting all input. We do this
396 * by moving the suffix pointer (fpnt) forward and incrementing
397 * sufflen by one, thereby yielding an additional two characters
398 * and allowing all output files to sort such that 'cat *' yields
399 * the input in order. I.e., the order is '... xyy xyz xzaaa
400 * xzaab ... xzyzy, xzyzz, xzzaaaa, xzzaaab' and so on.
402 if (!dflag && autosfx && (fpnt[0] == 'y') &&
403 strspn(fpnt+1, "z") == strlen(fpnt+1)) {
404 fpnt = fname + strlen(fname) - sufflen;
405 fpnt[sufflen + 2] = '\0';
417 /* Reset so we start back at all 'a's in our extended suffix. */
421 /* maxfiles = pattlen^sufflen, but don't use libm. */
422 for (maxfiles = 1, i = 0; i < sufflen; i++)
423 if (LONG_MAX / pattlen < maxfiles)
424 errx(EX_USAGE, "suffix is too long (max %ld)", i);
428 if (fnum == maxfiles)
429 errx(EX_DATAERR, "too many files");
431 /* Generate suffix of sufflen letters */
435 fpnt[i] = tfnum % pattlen + beg;
438 fpnt[sufflen] = '\0';
441 if ((ofd = open(fname, flags, DEFFILEMODE)) < 0) {
442 if (!clobber && errno == EEXIST)
444 err(EX_IOERR, "%s", fname);
452 (void)fprintf(stderr,
453 "usage: split [-cd] [-l line_count] [-a suffix_length] [file [prefix]]\n"
454 " split [-cd] -b byte_count[K|k|M|m|G|g] [-a suffix_length] [file [prefix]]\n"
455 " split [-cd] -n chunk_count [-a suffix_length] [file [prefix]]\n"
456 " split [-cd] -p pattern [-a suffix_length] [file [prefix]]\n");