cut.c revision 97234
1/*
2 * Copyright (c) 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Adam S. Moskowitz of Menlo Consulting and Marciano Pitargue.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38static const char copyright[] =
39"@(#) Copyright (c) 1989, 1993\n\
40	The Regents of the University of California.  All rights reserved.\n";
41static const char sccsid[] = "@(#)cut.c	8.3 (Berkeley) 5/4/95";
42static const char rcsid[] =
43  "$FreeBSD: head/usr.bin/cut/cut.c 97234 2002-05-24 09:11:18Z tjr $";
44#endif /* not lint */
45
46#include <ctype.h>
47#include <err.h>
48#include <limits.h>
49#include <locale.h>
50#include <stdio.h>
51#include <stdlib.h>
52#include <string.h>
53#include <unistd.h>
54
55int	cflag;
56char	dchar;
57int	dflag;
58int	fflag;
59int	sflag;
60
61void	c_cut (FILE *, const char *);
62void	f_cut (FILE *, const char *);
63void	get_list (char *);
64int	main (int, char **);
65void	needpos(size_t);
66static 	void usage (void);
67
68int
69main(argc, argv)
70	int argc;
71	char *argv[];
72{
73	FILE *fp;
74	void (*fcn) (FILE *, const char *) = NULL;
75	int ch, rval;
76
77	fcn = NULL;
78	setlocale (LC_ALL, "");
79
80	dchar = '\t';			/* default delimiter is \t */
81
82	/* Since we don't support multi-byte characters, the -c and -b
83	   options are equivalent, and the -n option is meaningless. */
84	while ((ch = getopt(argc, argv, "b:c:d:f:sn")) != -1)
85		switch(ch) {
86		case 'b':
87		case 'c':
88			fcn = c_cut;
89			get_list(optarg);
90			cflag = 1;
91			break;
92		case 'd':
93			dchar = *optarg;
94			dflag = 1;
95			break;
96		case 'f':
97			get_list(optarg);
98			fcn = f_cut;
99			fflag = 1;
100			break;
101		case 's':
102			sflag = 1;
103			break;
104		case 'n':
105			break;
106		case '?':
107		default:
108			usage();
109		}
110	argc -= optind;
111	argv += optind;
112
113	if (fflag) {
114		if (cflag)
115			usage();
116	} else if (!cflag || dflag || sflag)
117		usage();
118
119	rval = 0;
120	if (*argv)
121		for (; *argv; ++argv) {
122			if (!(fp = fopen(*argv, "r"))) {
123				warn("%s", *argv);
124				rval = 1;
125				continue;
126			}
127			fcn(fp, *argv);
128			(void)fclose(fp);
129		}
130	else
131		fcn(stdin, "stdin");
132	exit(rval);
133}
134
135size_t autostart, autostop, maxval;
136
137char *positions;
138
139void
140get_list(list)
141	char *list;
142{
143	size_t setautostart, start, stop;
144	char *pos;
145	char *p;
146
147	/*
148	 * set a byte in the positions array to indicate if a field or
149	 * column is to be selected; use +1, it's 1-based, not 0-based.
150	 * This parser is less restrictive than the Draft 9 POSIX spec.
151	 * POSIX doesn't allow lists that aren't in increasing order or
152	 * overlapping lists.  We also handle "-3-5" although there's no
153	 * real reason too.
154	 */
155	for (; (p = strsep(&list, ", \t")) != NULL;) {
156		setautostart = start = stop = 0;
157		if (*p == '-') {
158			++p;
159			setautostart = 1;
160		}
161		if (isdigit((unsigned char)*p)) {
162			start = stop = strtol(p, &p, 10);
163			if (setautostart && start > autostart)
164				autostart = start;
165		}
166		if (*p == '-') {
167			if (isdigit((unsigned char)p[1]))
168				stop = strtol(p + 1, &p, 10);
169			if (*p == '-') {
170				++p;
171				if (!autostop || autostop > stop)
172					autostop = stop;
173			}
174		}
175		if (*p)
176			errx(1, "[-cf] list: illegal list value");
177		if (!stop || !start)
178			errx(1, "[-cf] list: values may not include zero");
179		if (maxval < stop) {
180			maxval = stop;
181			needpos(maxval + 1);
182		}
183		for (pos = positions + start; start++ <= stop; *pos++ = 1);
184	}
185
186	/* overlapping ranges */
187	if (autostop && maxval > autostop) {
188		maxval = autostop;
189		needpos(maxval + 1);
190	}
191
192	/* set autostart */
193	if (autostart)
194		memset(positions + 1, '1', autostart);
195}
196
197void
198needpos(size_t n)
199{
200	static size_t npos;
201
202	/* Grow the positions array to at least the specified size. */
203	if (n > npos) {
204		if (npos == 0)
205			npos = n;
206		while (n > npos)
207			npos *= 2;
208		if ((positions = realloc(positions, npos)) == NULL)
209			err(1, "realloc");
210	}
211}
212
213/* ARGSUSED */
214void
215c_cut(fp, fname)
216	FILE *fp;
217	const char *fname;
218{
219	int ch, col;
220	char *pos;
221	fname = NULL;
222
223	ch = 0;
224	for (;;) {
225		pos = positions + 1;
226		for (col = maxval; col; --col) {
227			if ((ch = getc(fp)) == EOF)
228				return;
229			if (ch == '\n')
230				break;
231			if (*pos++)
232				(void)putchar(ch);
233		}
234		if (ch != '\n') {
235			if (autostop)
236				while ((ch = getc(fp)) != EOF && ch != '\n')
237					(void)putchar(ch);
238			else
239				while ((ch = getc(fp)) != EOF && ch != '\n');
240		}
241		(void)putchar('\n');
242	}
243}
244
245void
246f_cut(fp, fname)
247	FILE *fp;
248	const char *fname __unused;
249{
250	int ch, field, isdelim;
251	char *pos, *p, sep;
252	int output;
253	char *lbuf, *mlbuf = NULL;
254	size_t lbuflen;
255
256	for (sep = dchar; (lbuf = fgetln(fp, &lbuflen)) != NULL;) {
257		/* Assert EOL has a newline. */
258		if (*(lbuf + lbuflen - 1) != '\n') {
259			/* Can't have > 1 line with no trailing newline. */
260			mlbuf = malloc(lbuflen + 1);
261			if (mlbuf == NULL)
262				err(1, "malloc");
263			memcpy(mlbuf, lbuf, lbuflen);
264			*(mlbuf + lbuflen) = '\n';
265			lbuf = mlbuf;
266		}
267		output = 0;
268		for (isdelim = 0, p = lbuf;; ++p) {
269			ch = *p;
270			/* this should work if newline is delimiter */
271			if (ch == sep)
272				isdelim = 1;
273			if (ch == '\n') {
274				if (!isdelim && !sflag)
275					(void)fwrite(lbuf, lbuflen, 1, stdout);
276				break;
277			}
278		}
279		if (!isdelim)
280			continue;
281
282		pos = positions + 1;
283		for (field = maxval, p = lbuf; field; --field, ++pos) {
284			if (*pos) {
285				if (output++)
286					(void)putchar(sep);
287				while ((ch = *p++) != '\n' && ch != sep)
288					(void)putchar(ch);
289			} else {
290				while ((ch = *p++) != '\n' && ch != sep)
291					continue;
292			}
293			if (ch == '\n')
294				break;
295		}
296		if (ch != '\n') {
297			if (autostop) {
298				if (output)
299					(void)putchar(sep);
300				for (; (ch = *p) != '\n'; ++p)
301					(void)putchar(ch);
302			} else
303				for (; (ch = *p) != '\n'; ++p);
304		}
305		(void)putchar('\n');
306	}
307	if (mlbuf != NULL)
308		free(mlbuf);
309}
310
311static void
312usage()
313{
314	(void)fprintf(stderr, "%s\n%s\n%s\n",
315		"usage: cut -b list [-n] [file ...]",
316		"       cut -c list [file ...]",
317		"       cut -f list [-s] [-d delim] [file ...]");
318	exit(1);
319}
320