cut.c revision 43532
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";
41#endif /* not lint */
42
43#ifndef lint
44static const char sccsid[] = "@(#)cut.c	8.3 (Berkeley) 5/4/95";
45#endif /* not lint */
46
47#include <ctype.h>
48#include <err.h>
49#include <errno.h>
50#include <limits.h>
51#include <locale.h>
52#include <stdio.h>
53#include <stdlib.h>
54#include <string.h>
55#include <unistd.h>
56
57int	cflag;
58char	dchar;
59int	dflag;
60int	fflag;
61int	sflag;
62
63void	c_cut __P((FILE *, char *));
64void	f_cut __P((FILE *, char *));
65void	get_list __P((char *));
66static void	usage __P((void));
67
68int
69main(argc, argv)
70	int argc;
71	char *argv[];
72{
73	FILE *fp;
74	void (*fcn) __P((FILE *, char *)) = NULL;
75	int ch;
76
77	setlocale (LC_ALL, "");
78
79	dchar = '\t';			/* default delimiter is \t */
80
81	/* Since we don't support multi-byte characters, the -c and -b
82	   options are equivalent, and the -n option is meaningless. */
83	while ((ch = getopt(argc, argv, "b:c:d:f:sn")) != -1)
84		switch(ch) {
85		case 'b':
86		case 'c':
87			fcn = c_cut;
88			get_list(optarg);
89			cflag = 1;
90			break;
91		case 'd':
92			dchar = *optarg;
93			dflag = 1;
94			break;
95		case 'f':
96			get_list(optarg);
97			fcn = f_cut;
98			fflag = 1;
99			break;
100		case 's':
101			sflag = 1;
102			break;
103		case 'n':
104			break;
105		case '?':
106		default:
107			usage();
108		}
109	argc -= optind;
110	argv += optind;
111
112	if (fflag) {
113		if (cflag)
114			usage();
115	} else if (!cflag || dflag || sflag)
116		usage();
117
118	if (*argv)
119		for (; *argv; ++argv) {
120			if (!(fp = fopen(*argv, "r")))
121				err(1, "%s", *argv);
122			fcn(fp, *argv);
123			(void)fclose(fp);
124		}
125	else
126		fcn(stdin, "stdin");
127	exit(0);
128}
129
130int autostart, autostop, maxval;
131
132char positions[_POSIX2_LINE_MAX + 1];
133
134void
135get_list(list)
136	char *list;
137{
138	register int setautostart, start, stop;
139	register char *pos;
140	char *p;
141
142	/*
143	 * set a byte in the positions array to indicate if a field or
144	 * column is to be selected; use +1, it's 1-based, not 0-based.
145	 * This parser is less restrictive than the Draft 9 POSIX spec.
146	 * POSIX doesn't allow lists that aren't in increasing order or
147	 * overlapping lists.  We also handle "-3-5" although there's no
148	 * real reason too.
149	 */
150	for (; (p = strsep(&list, ", \t"));) {
151		setautostart = start = stop = 0;
152		if (*p == '-') {
153			++p;
154			setautostart = 1;
155		}
156		if (isdigit(*p)) {
157			start = stop = strtol(p, &p, 10);
158			if (setautostart && start > autostart)
159				autostart = start;
160		}
161		if (*p == '-') {
162			if (isdigit(p[1]))
163				stop = strtol(p + 1, &p, 10);
164			if (*p == '-') {
165				++p;
166				if (!autostop || autostop > stop)
167					autostop = stop;
168			}
169		}
170		if (*p)
171			errx(1, "[-cf] list: illegal list value");
172		if (!stop || !start)
173			errx(1, "[-cf] list: values may not include zero");
174		if (stop > _POSIX2_LINE_MAX)
175			errx(1, "[-cf] list: %d too large (max %d)",
176			    stop, _POSIX2_LINE_MAX);
177		if (maxval < stop)
178			maxval = stop;
179		for (pos = positions + start; start++ <= stop; *pos++ = 1);
180	}
181
182	/* overlapping ranges */
183	if (autostop && maxval > autostop)
184		maxval = autostop;
185
186	/* set autostart */
187	if (autostart)
188		memset(positions + 1, '1', autostart);
189}
190
191/* ARGSUSED */
192void
193c_cut(fp, fname)
194	FILE *fp;
195	char *fname;
196{
197	register int ch = 0, col;
198	register char *pos;
199
200	for (;;) {
201		pos = positions + 1;
202		for (col = maxval; col; --col) {
203			if ((ch = getc(fp)) == EOF)
204				return;
205			if (ch == '\n')
206				break;
207			if (*pos++)
208				(void)putchar(ch);
209		}
210		if (ch != '\n')
211			if (autostop)
212				while ((ch = getc(fp)) != EOF && ch != '\n')
213					(void)putchar(ch);
214			else
215				while ((ch = getc(fp)) != EOF && ch != '\n');
216		(void)putchar('\n');
217	}
218}
219
220void
221f_cut(fp, fname)
222	FILE *fp;
223	char *fname;
224{
225	register int ch, field, isdelim;
226	register char *pos, *p, sep;
227	int output;
228	char lbuf[_POSIX2_LINE_MAX + 1];
229
230	for (sep = dchar; fgets(lbuf, sizeof(lbuf), fp);) {
231		output = 0;
232		for (isdelim = 0, p = lbuf;; ++p) {
233			if (!(ch = *p))
234				errx(1, "%s: line too long.", fname);
235			/* this should work if newline is delimiter */
236			if (ch == sep)
237				isdelim = 1;
238			if (ch == '\n') {
239				if (!isdelim && !sflag)
240					(void)printf("%s", lbuf);
241				break;
242			}
243		}
244		if (!isdelim)
245			continue;
246
247		pos = positions + 1;
248		for (field = maxval, p = lbuf; field; --field, ++pos) {
249			if (*pos) {
250				if (output++)
251					(void)putchar(sep);
252				while ((ch = *p++) != '\n' && ch != sep)
253					(void)putchar(ch);
254			} else
255				while ((ch = *p++) != '\n' && ch != sep);
256			if (ch == '\n')
257				break;
258		}
259		if (ch != '\n')
260			if (autostop) {
261				if (output)
262					(void)putchar(sep);
263				for (; (ch = *p) != '\n'; ++p)
264					(void)putchar(ch);
265			} else
266				for (; (ch = *p) != '\n'; ++p);
267		(void)putchar('\n');
268	}
269}
270
271static void
272usage()
273{
274	(void)fprintf(stderr, "%s\n%s\n%s\n",
275		"usage: cut -b list [-n] [file ...]",
276		"       cut -c list [file ...]",
277		"       cut -f list [-s] [-d delim] [file ...]");
278	exit(1);
279}
280