Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 22 Mar 2002 18:42:25 +1100 (EST)
From:      "Tim J. Robbins" <tim@robbins.dropbear.id.au>
To:        FreeBSD-gnats-submit@FreeBSD.org
Subject:   standards/36191: P1003.1-2001 csplit utility
Message-ID:  <200203220742.g2M7gPw01928@descent.robbins.dropbear.id.au>

next in thread | raw e-mail | index | archive | help

>Number:         36191
>Category:       standards
>Synopsis:       P1003.1-2001 csplit utility
>Confidential:   no
>Severity:       non-critical
>Priority:       low
>Responsible:    freebsd-standards
>State:          open
>Quarter:        
>Keywords:       
>Date-Required:
>Class:          change-request
>Submitter-Id:   current-users
>Arrival-Date:   Thu Mar 21 23:50:01 PST 2002
>Closed-Date:
>Last-Modified:
>Originator:     Tim J. Robbins
>Release:        FreeBSD 4.5-STABLE i386
>Organization:
>Environment:
System: FreeBSD descent.robbins.dropbear.id.au 4.5-STABLE FreeBSD 4.5-STABLE #17: Thu Mar 21 19:48:18 EST 2002 tim@descent.robbins.dropbear.id.au:/usr/obj/usr/src/sys/DESCENT i386


	
>Description:
FreeBSD is missing the P1003.1-2001 csplit utililty.
>How-To-Repeat:
csplit
>Fix:

Here's an implementation of csplit.

# This is a shell archive.  Save it in a file, remove anything before
# this line, and then unpack it by entering "sh file".  Note, it may
# create directories; files and directories will be owned by you and
# have default permissions.
#
# This archive contains:
#
#	Makefile
#	csplit.c
#	csplit.1
#
echo x - Makefile
sed 's/^X//' >Makefile << 'END-of-Makefile'
X# $FreeBSD$
X# $Id: Makefile,v 1.1 2002/02/15 06:40:51 tim Exp $
X
XPROG=	csplit
X
X.include <bsd.prog.mk>
END-of-Makefile
echo x - csplit.c
sed 's/^X//' >csplit.c << 'END-of-csplit.c'
X/*-
X * Copyright (c) 2002 Tim J. Robbins.
X * All rights reserved.
X *
X * Redistribution and use in source and binary forms, with or without
X * modification, are permitted provided that the following conditions
X * are met:
X * 1. Redistributions of source code must retain the above copyright
X *    notice, this list of conditions and the following disclaimer.
X * 2. Redistributions in binary form must reproduce the above copyright
X *    notice, this list of conditions and the following disclaimer in the
X *    documentation and/or other materials provided with the distribution.
X *
X * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
X * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
X * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
X * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
X * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
X * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
X * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
X * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
X * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
X * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
X * SUCH DAMAGE.
X */
X
X/*
X * csplit -- split files based on context
X *
X * This utility splits its input into numbered output files by line number
X * or by a regular expression. Regular expression matches have an optional
X * offset with them, allowing the split to occur a specified number of
X * lines before or after the match.
X *
X * To handle negative offsets, we stop reading when the match occurs and
X * store the offset that the file should have been split at, then use
X * this output file as input until all the "overflowed" lines have been read.
X * The file is then closed and truncated to the correct length.
X *
X * We assume that the output files can be seeked upon (ie. they cannot be
X * symlinks to named pipes or character devices), but make no such
X * assumption about the input.
X */
X
X#include <sys/cdefs.h>
X__FBSDID("$FreeBSD$");
X__RCSID("$Id: csplit.c,v 1.17 2002/03/22 07:39:55 tim Exp $");
X
X#include <sys/types.h>
X
X#include <ctype.h>
X#include <err.h>
X#include <errno.h>
X#include <limits.h>
X#include <regex.h>
X#include <stdio.h>
X#include <stdlib.h>
X#include <string.h>
X#include <unistd.h>
X
Xvoid cleanup(void);
Xvoid do_lineno(const char *expr);
Xvoid do_rexp(const char *expr);
Xchar *getline(void);
XFILE *newfile(void);
Xvoid toomuch(FILE *ofp, long n);
Xvoid usage(void);
X
X/*
X * Command line options
X */
Xconst char *prefix;		/* File name prefix */
Xlong sufflen;			/* Number of decimal digits for suffix */
Xint sflag;			/* Suppress output of file names */
Xint kflag;			/* Keep output if error occurs */
X
X/*
X * Other miscellaneous globals (XXX too many)
X */
Xlong lineno;			/* Current line number in input file */
Xlong reps;			/* Number of repetitions for this pattern */
Xlong nfiles;			/* Number of files output so far */
Xchar currfile[PATH_MAX];	/* Current output file */
Xconst char *infn;		/* Name of the input file */
XFILE *infile;			/* Input file handle */
XFILE *overfile;			/* Overflow file for toomuch() */
Xoff_t truncofs;			/* Offset this file should be truncated at */
Xint doclean;			/* Should cleanup() remove output? */
X
X/* Create a new output file */
XFILE *
Xnewfile(void)
X{
X	char fmt[20];
X	FILE *fp;
X
X	sprintf(fmt, "%%s%%0%ldld", sufflen);
X	sprintf(currfile, fmt, prefix, nfiles);
X	if ((fp = fopen(currfile, "w+")) == NULL)
X		err(1, "%s", currfile);
X	nfiles++;
X
X	return (fp);
X}
X
X/* Remove partial output, called before exiting. */
Xvoid
Xcleanup(void)
X{
X	char fmt[20], fnbuf[PATH_MAX];
X	long i;
X
X	if (!doclean)
X		return;
X
X	for (i = 0; i < nfiles; i++) {
X		sprintf(fmt, "%%s%%0%ldld", sufflen);
X		sprintf(fnbuf, fmt, prefix, i);
X		unlink(fnbuf);
X	}
X}
X
X/* Read a line from the input */
Xchar *
Xgetline(void)
X{
X	static char lbuf[LINE_MAX];
X	FILE *src;
X
X	src = overfile != NULL ? overfile : infile;
X
Xagain: if (fgets(lbuf, sizeof(lbuf), src) == NULL) {
X		if (src == overfile) {
X			src = infile;
X			goto again;
X		}
X		return (NULL);
X	}
X	lineno++;
X	if (strchr(lbuf, '\n') == NULL)
X		errx(1, "%s:%ld: line too long", infn, lineno);
X	if (ferror(src))
X		err(1, "%s", infn);
X
X	return (lbuf);
X}
X
X/* Conceptually rewind the input (as obtained by getline()) back `n' lines */
Xvoid
Xtoomuch(FILE *ofp, long n)
X{
X	char buf[BUFSIZ];
X	size_t nread, i;
X
X	if (overfile != NULL) {
X		/*
X		 * Truncate the previous file we overflowed into back to
X		 * the correct length, close it.
X		 */
X		if (fflush(overfile) != 0)
X			err(1, "overflow");
X		if (ftruncate(fileno(overfile), truncofs) != 0)
X			err(1, "overflow");
X		if (fclose(overfile) != 0)
X			err(1, "overflow");
X		overfile = NULL;
X	}
X
X	if (n == 0)
X		/* Just tidying up */
X		return;
X
X	lineno -= n;
X
X	/*
X	 * Wind the overflow file backwards to `n' lines before the
X	 * current one.
X	 */
X	do {
X		/* Back a chunk */
X		if (ftello(ofp) < (off_t)sizeof(buf))
X			rewind(ofp);
X		else
X			fseek(ofp, -(long)sizeof(buf), SEEK_CUR);
X		if (ferror(ofp))
X			errx(1, "%s: can't seek", currfile);
X		if ((nread = fread(buf, 1, sizeof(buf), ofp)) == 0)
X			errx(1, "can't read overflowed output");
X		if (fseek(ofp, -(long)nread, SEEK_CUR) != 0)
X			err(1, "%s", currfile);
X		for (i = 0; i < nread; i++)
X			if (buf[nread - i] == '\n' && n-- == 0)
X				break;
X	} while (n > 0);
X	if (fseek(ofp, nread - i + 1, SEEK_CUR) != 0)
X		err(1, "%s", currfile);
X
X	/*
X	 * getline() will read from here. Next call will truncate to
X	 * truncofs in this file.
X	 */
X	overfile = ofp;
X	truncofs = ftello(overfile);
X}
X
X/* Handle splits for /regexp/ and %regexp% patterns */
Xvoid
Xdo_rexp(const char *expr)
X{
X	regex_t cre;
X	long long nwritten;
X	long ofs;
X	char *ecopy, *ep, *p, *pofs, *re;
X	FILE *ofp;
X	int first;
X
X	if ((ecopy = strdup(expr)) == NULL)
X		err(1, NULL);
X
X	re = ecopy + 1;	/* point to first char of regexp */
X	if ((pofs = strrchr(ecopy, *expr)) == NULL || pofs[-1] == '\\')
X		errx(1, "%s: missing trailing %c", expr, *expr);
X	*pofs++ = '\0'; /* point to offset from regexp, zap trailing char */
X
X	if (*pofs != '\0') {
X		if (*pofs != '+' && *pofs != '-')
X			errx(1, "%s: bad offset", pofs);
X		errno = 0;
X		ofs = strtol(pofs, &ep, 10);
X		if (ofs < 0 || *ep != '\0' || errno != 0)
X			errx(1, "%s: bad offset", pofs);
X	} else
X		ofs = 0;
X
X	if (regcomp(&cre, re, REG_BASIC|REG_NOSUB) != 0)
X		errx(1, "%s: bad regular expression", re);
X
X	if (*expr == '/')
X		/* /regexp/: Save results to a file */
X		ofp = newfile();
X	else
X		/* %regexp%: Make a temporary file for overflow */
X		ofp = tmpfile();
X
X	/* Read and output lines until we get a match */
X	first = 1;
X	while ((p = getline()) != NULL) {
X		if (fputs(p, ofp) != 0)
X			break;
X		if (!first && regexec(&cre, p, 0, NULL, 0) == 0)
X			break;
X		first = 0;
X	}
X
X	if (ofs <= 0) {
X		/*
X		 * Negative (or zero) offset: throw back any lines we should
X		 * not have read yet.
X		  */
X		if (p != NULL) {
X			toomuch(ofp, -ofs + 1);
X			nwritten = (long long)truncofs;
X		} else
X			nwritten = (long long)ftello(ofp);
X	} else {
X		/*
X		 * Positive offset: copy the requested number of lines
X		 * after the match.
X		 */
X		while (--ofs > 0 && (p = getline()) != NULL)
X			fputs(p, ofp);
X		toomuch(NULL, 0);
X		nwritten = (long long)ftello(ofp);
X		if (fclose(ofp) != 0)
X			err(1, "%s", currfile);
X	}
X
X	if (!sflag && *expr == '/')
X		printf("%lld\n", (long long)nwritten);
X
X	regfree(&cre);
X	free(ecopy);
X}
X
X/* Handle splits based on line number */
Xvoid
Xdo_lineno(const char *expr)
X{
X	long tgtline, lastline;
X	char *p, *ep;
X	FILE *ofp;
X
X	errno = 0;
X	tgtline = strtol(expr, &ep, 10);
X	if (tgtline <= 0 || errno != 0 || *ep != '\0')
X		errx(1, "%s: bad line number", expr);
X	lastline = tgtline;
X	if (lastline <= lineno)
X		errx(1, "%s: can't go backwards", expr);
X
X	for (;;) {
X		ofp = newfile();
X		while (lineno + 1 != lastline)
X			if ((p = getline()) == NULL || fputs(p, ofp) != 0)
X				break;
X		if (!sflag)
X			printf("%lld\n", (long long)ftello(ofp));
X		if (fclose(ofp) != 0)
X			err(1, "%s", currfile);
X		if (reps-- == 0)
X			break;
X		lastline += tgtline;
X	} 
X}
X
Xint
Xmain(int argc, char *argv[])
X{
X	const char *expr;
X	char *ep, *p;
X	FILE *ofp;
X	int ch;
X
X	kflag = sflag = 0;
X	prefix = "xx";
X	sufflen = 2;
X	while ((ch = getopt(argc, argv, "ksf:n:")) > 0) {
X		switch (ch) {
X		case 'f':
X			prefix = optarg;
X			break;
X		case 'k':
X			kflag = 1;
X			break;
X		case 'n':
X			errno = 0;
X			sufflen = strtol(optarg, &ep, 10);
X			if (sufflen <= 0 || *ep != '\0' || errno != 0)
X				errx(1, "%s: bad suffix length", optarg);
X			break;
X		case 's':
X			sflag = 1;
X			break;
X		default:
X			usage();
X			/*NOTREACHED*/
X		}
X	}
X
X	if (sufflen + strlen(prefix) >= PATH_MAX)
X		errx(1, "name too long");
X
X	argc -= optind;
X	argv += optind;
X
X	if ((infn = *argv++) == NULL)
X		usage();
X	if (strcmp(infn, "-") == 0) {
X		infile = stdin;
X		infn = "stdin";
X	} else if ((infile = fopen(infn, "r")) == NULL)
X		err(1, "%s", infn);
X
X	if (!kflag) {
X		doclean = 1;
X		atexit(cleanup);
X	}
X
X	lineno = 0;
X	nfiles = 0;
X	truncofs = 0;
X	overfile = NULL;
X
X	while ((expr = *argv++) != NULL) {
X		/* Look ahead & see if this pattern has any repetitions */
X		if (*argv != NULL && **argv == '{') {
X			errno = 0;
X			reps = strtol(*argv + 1, &ep, 10);
X			if (reps < 0 || *ep != '}' || errno != 0)
X				errx(1, "%s: bad repetitions", expr);
X			argv++;
X		} else
X			reps = 0;
X
X		if (*expr == '/' || *expr == '%') {
X			/* Regular expression copy or ignore */
X			do
X				do_rexp(expr);
X			while (reps-- != 0);
X		} else if (isdigit(*expr))
X			do_lineno(expr);
X		else
X			errx(1, "bad expression %s", expr);
X	}
X
X	/* Copy the rest into a new file */
X	if (!feof(infile)) {
X		ofp = newfile();
X		while ((p = getline()) != NULL && fputs(p, ofp) == 0)
X			;
X		if (!sflag)
X			printf("%lld\n", (long long)ftell(ofp));
X		if (fclose(ofp) != 0)
X			err(1, "%s", currfile);
X	}
X
X	toomuch(NULL, 0);
X	doclean = 0;
X
X	return (0);
X}
X
Xvoid
Xusage(void)
X{
X	fprintf(stderr,
X"usage: csplit [-ks] [-f prefix] [-n number] file [args ...]\n");
X	exit(1);
X}
END-of-csplit.c
echo x - csplit.1
sed 's/^X//' >csplit.1 << 'END-of-csplit.1'
X.\" Copyright (c) 2002 Tim J. Robbins.
X.\" All rights reserved.
X.\"
X.\" Redistribution and use in source and binary forms, with or without
X.\" modification, are permitted provided that the following conditions
X.\" are met:
X.\" 1. Redistributions of source code must retain the above copyright
X.\"    notice, this list of conditions and the following disclaimer.
X.\" 2. Redistributions in binary form must reproduce the above copyright
X.\"    notice, this list of conditions and the following disclaimer in the
X.\"    documentation and/or other materials provided with the distribution.
X.\"
X.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
X.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
X.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
X.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
X.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
X.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
X.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
X.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
X.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
X.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
X.\" SUCH DAMAGE.
X.\"
X.\" $FreeBSD$
X.\" $Id: csplit.1,v 1.8 2002/02/20 12:52:11 tim Exp $
X.\"
X.Dd February 20, 2002
X.Dt CSPLIT 1
X.Os
X.Sh NAME
X.Nm csplit
X.Nd split files based on context
X.Sh SYNOPSIS
X.Nm
X.Op Fl ks
X.Op Fl f Ar prefix
X.Op Fl n Ar number
X.Ar file
X.Bk
X.Op Ar args ...
X.Ek
X.Sh DESCRIPTION
XThe
X.Nm
Xutility splits
X.Ar file
Xinto pieces using the patterns
X.Ar args... .
XIf
X.Ar file
Xis
Xa dash
X.Pq Sq \&- ,
X.Nm
Xreads from standard input.
X.Pp
XThe options are as follows:
X.Bl -tag -width indent
X.It Fl f Ar prefix
XName the created files beginning with
X.Ar prefix .
XThe default is
X.Dq Pa xx .
X.It Fl k
XDo not remove output files if an error occurs.
X.It Fl n Ar number
XUse
X.Ar number
Xof decimal digits after the
X.Ar prefix
Xto form the file name. The default is 2.
X.It Fl s
XDo not write the size of each output file.
X.El
X.Pp
XThe
X.Ar args...
Xoperands may be a combination of the following:
X.Bl -tag -width "line_no"
X.It Em /regexp/[[+|-]offset]
XCreate a file containing the input from the current line to (but not including)
Xthe next line matching the given basic regular expression.
X.It Em %regexp%[[+|-]offset]
XSame as above but a file is not created for the output.
X.It Em line_no
XCreate containing the input from the current line to (but not including)
Xthe specified line number.
X.It Em {num}
XRepeat the previous pattern the specified number of times.
XIf it follows a line number pattern, a new file will be created for each
X.Em line_no
Xlines,
X.Em num
Xtimes.
XThe first line of the file is line number 1 for historic reasons.
X.El
X.Pp
XAfter all the patterns have been processed, the remaining input data
X(if there is any) will be written to a new file.
X.Pp
XRequesting to split at a line before the current line number will result
Xin an error.
X.Sh EXAMPLES
XSplit the
X.Xr mdoc 7
Xfile
X.Pa foo.1
Xinto one file for each section (up to 20):
X.Pp
X.D1 Ic csplit foo.1 %^\\.Sh% /^\\.Sh/ {20}
X.Pp
XSplit standard input into 66 line pages.
X.Pp
X.D1 Ic csplit - 67 66 {19}
X.Sh DIAGNOSTICS
X.Ex -std
X.Sh COMPATIBILITY
XSome implementations of
X.Nm
Xcannot work with input files that are not regular files. This implementation
Xdoes not share this problem.
X.Sh SEE ALSO
X.Xr sed 1 ,
X.Xr split 1 ,
X.Xr re_format 7
X.Sh STANDARDS
XThe
X.Nm
Xutility is expected to comply with the
X.St -p1003.1-2001
Xspecification.
X.Pp
XThe ability to specify a file argument of
X.Sq \&-
Xto read from standard input is a
X.Fx
Xextension.
END-of-csplit.1
exit

>Release-Note:
>Audit-Trail:
>Unformatted:

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-standards" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200203220742.g2M7gPw01928>