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>
33 __FBSDID("$FreeBSD$");
36 static const char copyright[] =
37 "@(#) Copyright (c) 1987, 1993, 1994\n\
38 The Regents of the University of California. All rights reserved.\n";
42 static const char sccsid[] = "@(#)split.c 8.2 (Berkeley) 4/16/94";
45 #include <sys/param.h>
46 #include <sys/types.h>
66 #define DEFLINE 1000 /* Default num lines per file. */
68 static off_t bytecnt; /* Byte count to split on. */
69 static off_t chunks = 0; /* Chunks count to split into. */
70 static bool clobber = true; /* Whether to overwrite existing output files. */
71 static long numlines; /* Line count to split on. */
72 static int file_open; /* If a file open. */
73 static int ifd = -1, ofd = -1; /* Input/output file descriptors. */
74 static char fname[MAXPATHLEN]; /* File name prefix. */
78 static long sufflen = 2; /* File name suffix length. */
79 static int autosfx = 1; /* Whether to auto-extend the suffix length. */
81 static void newfile(void);
82 static void split1(void);
83 static void split2(void);
84 static void split3(void);
85 static void usage(void) __dead2;
88 main(int argc, char **argv)
94 setlocale(LC_ALL, "");
97 while ((ch = getopt(argc, argv, "0123456789a:b:cdl:n:p:")) != -1)
99 case '0': case '1': case '2': case '3': case '4':
100 case '5': case '6': case '7': case '8': case '9':
102 * Undocumented kludge: split was originally designed
103 * to take a number after a dash.
106 p = argv[optind - 1];
107 if (p[0] == '-' && p[1] == ch && !p[2])
108 numlines = strtol(++p, &ep, 10);
111 strtol(argv[optind] + 1, &ep, 10);
112 if (numlines <= 0 || *ep)
114 "%s: illegal line count", optarg);
117 case 'a': /* Suffix length */
118 if ((sufflen = strtol(optarg, &ep, 10)) <= 0 || *ep)
120 "%s: illegal suffix length", optarg);
123 case 'b': /* Byte count. */
125 error = expand_number(optarg, &bytecnt);
127 errx(EX_USAGE, "%s: offset too large", optarg);
129 case 'c': /* Continue, don't overwrite output files. */
132 case 'd': /* Decimal suffix */
135 case 'l': /* Line count. */
138 if ((numlines = strtol(optarg, &ep, 10)) <= 0 || *ep)
140 "%s: illegal line count", optarg);
142 case 'n': /* Chunks. */
143 if (!isdigit((unsigned char)optarg[0]) ||
144 (chunks = (size_t)strtoul(optarg, &ep, 10)) == 0 ||
146 errx(EX_USAGE, "%s: illegal number of chunks",
151 case 'p': /* pattern matching. */
152 if (regcomp(&rgx, optarg, REG_EXTENDED|REG_NOSUB) != 0)
153 errx(EX_USAGE, "%s: illegal regexp", optarg);
162 if (*argv != NULL) { /* Input file. */
163 if (strcmp(*argv, "-") == 0)
165 else if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
166 err(EX_NOINPUT, "%s", *argv);
169 if (*argv != NULL) /* File name prefix. */
170 if (strlcpy(fname, *argv++, sizeof(fname)) >= sizeof(fname))
171 errx(EX_USAGE, "file name prefix is too long");
175 if (strlen(fname) + (unsigned long)sufflen >= sizeof(fname))
176 errx(EX_USAGE, "suffix is too long");
177 if (pflag && (numlines != 0 || bytecnt != 0 || chunks != 0))
182 else if (bytecnt != 0 || chunks != 0)
185 if (bytecnt && chunks)
188 if (ifd == -1) /* Stdin by default. */
206 * Split the input by bytes.
211 static char bfr[MAXBSIZE];
220 switch ((len = read(ifd, bfr, sizeof(bfr)))) {
224 err(EX_IOERR, "read");
228 if (!chunks || (nfiles < chunks)) {
233 if (bcnt + len >= bytecnt) {
234 dist = bytecnt - bcnt;
235 if (write(ofd, bfr, dist) != dist)
236 err(EX_IOERR, "write");
238 for (C = bfr + dist; len >= bytecnt;
239 len -= bytecnt, C += bytecnt) {
240 if (!chunks || (nfiles < chunks)) {
245 C, bytecnt) != bytecnt)
246 err(EX_IOERR, "write");
249 if (!chunks || (nfiles < chunks)) {
253 if (write(ofd, C, len) != len)
254 err(EX_IOERR, "write");
260 if (write(ofd, bfr, len) != len)
261 err(EX_IOERR, "write");
268 * Split the input by lines.
282 /* Stick a stream on top of input file descriptor */
283 if ((infp = fdopen(ifd, "r")) == NULL)
284 err(EX_NOINPUT, "fdopen");
286 /* Process input one line at a time */
287 while ((errno = 0, len = getline(&buf, &bufsize, infp)) > 0) {
288 /* Check if we need to start a new file */
293 pmatch.rm_eo = len - 1;
294 if (regexec(&rgx, buf, 0, &pmatch, REG_STARTEND) == 0)
296 } else if (lcnt++ == numlines) {
301 /* Open output file if needed */
306 if (write(ofd, buf, len) != len)
307 err(EX_IOERR, "write");
311 if ((len == -1 && errno != 0) || ferror(infp))
312 err(EX_IOERR, "read");
319 * Split the input into specified number of chunks
326 if (fstat(ifd, &sb) == -1) {
331 if (chunks > sb.st_size) {
332 errx(1, "can't split into more than %d files",
337 bytecnt = sb.st_size / chunks;
344 * Open a new output file.
349 long i, maxfiles, tfnum;
354 int flags = O_WRONLY | O_CREAT | O_TRUNC;
360 if (fname[0] == '\0') {
364 fpnt = fname + strlen(fname);
366 } else if (close(ofd) != 0)
378 pattlen = end - beg + 1;
381 * If '-a' is not specified, then we automatically expand the
382 * suffix length to accomodate splitting all input. We do this
383 * by moving the suffix pointer (fpnt) forward and incrementing
384 * sufflen by one, thereby yielding an additional two characters
385 * and allowing all output files to sort such that 'cat *' yields
386 * the input in order. I.e., the order is '... xyy xyz xzaaa
387 * xzaab ... xzyzy, xzyzz, xzzaaaa, xzzaaab' and so on.
389 if (!dflag && autosfx && (fpnt[0] == 'y') &&
390 strspn(fpnt+1, "z") == strlen(fpnt+1)) {
391 fpnt = fname + strlen(fname) - sufflen;
392 fpnt[sufflen + 2] = '\0';
404 /* Reset so we start back at all 'a's in our extended suffix. */
409 /* maxfiles = pattlen^sufflen, but don't use libm. */
410 for (maxfiles = 1, i = 0; i < sufflen; i++)
411 if (LONG_MAX / pattlen < maxfiles)
412 errx(EX_USAGE, "suffix is too long (max %ld)", i);
416 if (fnum == maxfiles)
417 errx(EX_DATAERR, "too many files");
419 /* Generate suffix of sufflen letters */
423 fpnt[i] = tfnum % pattlen + beg;
426 fpnt[sufflen] = '\0';
429 if ((ofd = open(fname, flags, DEFFILEMODE)) < 0) {
430 if (!clobber && errno == EEXIST)
432 err(EX_IOERR, "%s", fname);
440 (void)fprintf(stderr,
441 "usage: split [-cd] [-l line_count] [-a suffix_length] [file [prefix]]\n"
442 " split [-cd] -b byte_count[K|k|M|m|G|g] [-a suffix_length] [file [prefix]]\n"
443 " split [-cd] -n chunk_count [-a suffix_length] [file [prefix]]\n"
444 " split [-cd] -p pattern [-a suffix_length] [file [prefix]]\n");