xref: /freebsd/usr.bin/cut/cut.c (revision 61e21613)
1 /*
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam S. Moskowitz of Menlo Consulting and Marciano Pitargue.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <ctype.h>
36 #include <err.h>
37 #include <errno.h>
38 #include <limits.h>
39 #include <locale.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <wchar.h>
45 
46 static int	bflag;
47 static int	cflag;
48 static wchar_t	dchar;
49 static char	dcharmb[MB_LEN_MAX + 1];
50 static int	dflag;
51 static int	fflag;
52 static int	nflag;
53 static int	sflag;
54 static int	wflag;
55 
56 static size_t	autostart, autostop, maxval;
57 static char *	positions;
58 
59 static int	b_cut(FILE *, const char *);
60 static int	b_n_cut(FILE *, const char *);
61 static int	c_cut(FILE *, const char *);
62 static int	f_cut(FILE *, const char *);
63 static void	get_list(char *);
64 static int	is_delim(wchar_t);
65 static void	needpos(size_t);
66 static void	usage(void);
67 
68 int
69 main(int argc, char *argv[])
70 {
71 	FILE *fp;
72 	int (*fcn)(FILE *, const char *);
73 	int ch, rval;
74 	size_t n;
75 
76 	setlocale(LC_ALL, "");
77 
78 	fcn = NULL;
79 	dchar = '\t';			/* default delimiter is \t */
80 	strcpy(dcharmb, "\t");
81 
82 	while ((ch = getopt(argc, argv, "b:c:d:f:snw")) != -1)
83 		switch(ch) {
84 		case 'b':
85 			get_list(optarg);
86 			bflag = 1;
87 			break;
88 		case 'c':
89 			get_list(optarg);
90 			cflag = 1;
91 			break;
92 		case 'd':
93 			n = mbrtowc(&dchar, optarg, MB_LEN_MAX, NULL);
94 			if (dchar == '\0' || n != strlen(optarg))
95 				errx(1, "bad delimiter");
96 			strcpy(dcharmb, optarg);
97 			dflag = 1;
98 			break;
99 		case 'f':
100 			get_list(optarg);
101 			fflag = 1;
102 			break;
103 		case 's':
104 			sflag = 1;
105 			break;
106 		case 'n':
107 			nflag = 1;
108 			break;
109 		case 'w':
110 			wflag = 1;
111 			break;
112 		case '?':
113 		default:
114 			usage();
115 		}
116 	argc -= optind;
117 	argv += optind;
118 
119 	if (fflag) {
120 		if (bflag || cflag || nflag || (wflag && dflag))
121 			usage();
122 	} else if (!(bflag || cflag) || dflag || sflag || wflag)
123 		usage();
124 	else if (!bflag && nflag)
125 		usage();
126 
127 	if (fflag)
128 		fcn = f_cut;
129 	else if (cflag)
130 		fcn = MB_CUR_MAX > 1 ? c_cut : b_cut;
131 	else if (bflag)
132 		fcn = nflag && MB_CUR_MAX > 1 ? b_n_cut : b_cut;
133 
134 	rval = 0;
135 	if (*argv)
136 		for (; *argv; ++argv) {
137 			if (strcmp(*argv, "-") == 0)
138 				rval |= fcn(stdin, "stdin");
139 			else {
140 				if (!(fp = fopen(*argv, "r"))) {
141 					warn("%s", *argv);
142 					rval = 1;
143 					continue;
144 				}
145 				fcn(fp, *argv);
146 				(void)fclose(fp);
147 			}
148 		}
149 	else
150 		rval = fcn(stdin, "stdin");
151 	exit(rval);
152 }
153 
154 static void
155 get_list(char *list)
156 {
157 	size_t setautostart, start, stop;
158 	char *pos;
159 	char *p;
160 
161 	/*
162 	 * set a byte in the positions array to indicate if a field or
163 	 * column is to be selected; use +1, it's 1-based, not 0-based.
164 	 * Numbers and number ranges may be overlapping, repeated, and in
165 	 * any order. We handle "-3-5" although there's no real reason to.
166 	 */
167 	for (; (p = strsep(&list, ", \t")) != NULL;) {
168 		setautostart = start = stop = 0;
169 		if (*p == '-') {
170 			++p;
171 			setautostart = 1;
172 		}
173 		if (isdigit((unsigned char)*p)) {
174 			start = stop = strtol(p, &p, 10);
175 			if (setautostart && start > autostart)
176 				autostart = start;
177 		}
178 		if (*p == '-') {
179 			if (isdigit((unsigned char)p[1]))
180 				stop = strtol(p + 1, &p, 10);
181 			if (*p == '-') {
182 				++p;
183 				if (!autostop || autostop > stop)
184 					autostop = stop;
185 			}
186 		}
187 		if (*p)
188 			errx(1, "[-bcf] list: illegal list value");
189 		if (!stop || !start)
190 			errx(1, "[-bcf] list: values may not include zero");
191 		if (maxval < stop) {
192 			maxval = stop;
193 			needpos(maxval + 1);
194 		}
195 		for (pos = positions + start; start++ <= stop; *pos++ = 1);
196 	}
197 
198 	/* overlapping ranges */
199 	if (autostop && maxval > autostop) {
200 		maxval = autostop;
201 		needpos(maxval + 1);
202 	}
203 
204 	/* reversed range with autostart */
205 	if (maxval < autostart) {
206 		maxval = autostart;
207 		needpos(maxval + 1);
208 	}
209 
210 	/* set autostart */
211 	if (autostart)
212 		memset(positions + 1, '1', autostart);
213 }
214 
215 static void
216 needpos(size_t n)
217 {
218 	static size_t npos;
219 	size_t oldnpos;
220 
221 	/* Grow the positions array to at least the specified size. */
222 	if (n > npos) {
223 		oldnpos = npos;
224 		if (npos == 0)
225 			npos = n;
226 		while (n > npos)
227 			npos *= 2;
228 		if ((positions = realloc(positions, npos)) == NULL)
229 			err(1, "realloc");
230 		memset((char *)positions + oldnpos, 0, npos - oldnpos);
231 	}
232 }
233 
234 static int
235 b_cut(FILE *fp, const char *fname __unused)
236 {
237 	int ch, col;
238 	char *pos;
239 
240 	ch = 0;
241 	for (;;) {
242 		pos = positions + 1;
243 		for (col = maxval; col; --col) {
244 			if ((ch = getc(fp)) == EOF)
245 				return (0);
246 			if (ch == '\n')
247 				break;
248 			if (*pos++)
249 				(void)putchar(ch);
250 		}
251 		if (ch != '\n') {
252 			if (autostop)
253 				while ((ch = getc(fp)) != EOF && ch != '\n')
254 					(void)putchar(ch);
255 			else
256 				while ((ch = getc(fp)) != EOF && ch != '\n');
257 		}
258 		(void)putchar('\n');
259 	}
260 	return (0);
261 }
262 
263 /*
264  * Cut based on byte positions, taking care not to split multibyte characters.
265  * Although this function also handles the case where -n is not specified,
266  * b_cut() ought to be much faster.
267  */
268 static int
269 b_n_cut(FILE *fp, const char *fname)
270 {
271 	size_t col, i, lbuflen;
272 	char *lbuf;
273 	int canwrite, clen, warned;
274 	mbstate_t mbs;
275 
276 	memset(&mbs, 0, sizeof(mbs));
277 	warned = 0;
278 	while ((lbuf = fgetln(fp, &lbuflen)) != NULL) {
279 		for (col = 0; lbuflen > 0; col += clen) {
280 			if ((clen = mbrlen(lbuf, lbuflen, &mbs)) < 0) {
281 				if (!warned) {
282 					warn("%s", fname);
283 					warned = 1;
284 				}
285 				memset(&mbs, 0, sizeof(mbs));
286 				clen = 1;
287 			}
288 			if (clen == 0 || *lbuf == '\n')
289 				break;
290 			if (col < maxval && !positions[1 + col]) {
291 				/*
292 				 * Print the character if (1) after an initial
293 				 * segment of un-selected bytes, the rest of
294 				 * it is selected, and (2) the last byte is
295 				 * selected.
296 				 */
297 				i = col;
298 				while (i < col + clen && i < maxval &&
299 				    !positions[1 + i])
300 					i++;
301 				canwrite = i < col + clen;
302 				for (; i < col + clen && i < maxval; i++)
303 					canwrite &= positions[1 + i];
304 				if (canwrite)
305 					fwrite(lbuf, 1, clen, stdout);
306 			} else {
307 				/*
308 				 * Print the character if all of it has
309 				 * been selected.
310 				 */
311 				canwrite = 1;
312 				for (i = col; i < col + clen; i++)
313 					if ((i >= maxval && !autostop) ||
314 					    (i < maxval && !positions[1 + i])) {
315 						canwrite = 0;
316 						break;
317 					}
318 				if (canwrite)
319 					fwrite(lbuf, 1, clen, stdout);
320 			}
321 			lbuf += clen;
322 			lbuflen -= clen;
323 		}
324 		if (lbuflen > 0)
325 			putchar('\n');
326 	}
327 	return (warned);
328 }
329 
330 static int
331 c_cut(FILE *fp, const char *fname)
332 {
333 	wint_t ch;
334 	int col;
335 	char *pos;
336 
337 	ch = 0;
338 	for (;;) {
339 		pos = positions + 1;
340 		for (col = maxval; col; --col) {
341 			if ((ch = getwc(fp)) == WEOF)
342 				goto out;
343 			if (ch == '\n')
344 				break;
345 			if (*pos++)
346 				(void)putwchar(ch);
347 		}
348 		if (ch != '\n') {
349 			if (autostop)
350 				while ((ch = getwc(fp)) != WEOF && ch != '\n')
351 					(void)putwchar(ch);
352 			else
353 				while ((ch = getwc(fp)) != WEOF && ch != '\n');
354 		}
355 		(void)putwchar('\n');
356 	}
357 out:
358 	if (ferror(fp)) {
359 		warn("%s", fname);
360 		return (1);
361 	}
362 	return (0);
363 }
364 
365 static int
366 is_delim(wchar_t ch)
367 {
368 	if (wflag) {
369 		if (ch == ' ' || ch == '\t')
370 			return 1;
371 	} else {
372 		if (ch == dchar)
373 			return 1;
374 	}
375 	return 0;
376 }
377 
378 static int
379 f_cut(FILE *fp, const char *fname)
380 {
381 	wchar_t ch;
382 	int field, i, isdelim;
383 	char *pos, *p;
384 	int output;
385 	char *lbuf, *mlbuf;
386 	size_t clen, lbuflen, reallen;
387 
388 	mlbuf = NULL;
389 	while ((lbuf = fgetln(fp, &lbuflen)) != NULL) {
390 		reallen = lbuflen;
391 		/* Assert EOL has a newline. */
392 		if (*(lbuf + lbuflen - 1) != '\n') {
393 			/* Can't have > 1 line with no trailing newline. */
394 			mlbuf = malloc(lbuflen + 1);
395 			if (mlbuf == NULL)
396 				err(1, "malloc");
397 			memcpy(mlbuf, lbuf, lbuflen);
398 			*(mlbuf + lbuflen) = '\n';
399 			lbuf = mlbuf;
400 			reallen++;
401 		}
402 		output = 0;
403 		for (isdelim = 0, p = lbuf;; p += clen) {
404 			clen = mbrtowc(&ch, p, lbuf + reallen - p, NULL);
405 			if (clen == (size_t)-1 || clen == (size_t)-2) {
406 				warnc(EILSEQ, "%s", fname);
407 				free(mlbuf);
408 				return (1);
409 			}
410 			if (clen == 0)
411 				clen = 1;
412 			/* this should work if newline is delimiter */
413 			if (is_delim(ch))
414 				isdelim = 1;
415 			if (ch == '\n') {
416 				if (!isdelim && !sflag)
417 					(void)fwrite(lbuf, lbuflen, 1, stdout);
418 				break;
419 			}
420 		}
421 		if (!isdelim)
422 			continue;
423 
424 		pos = positions + 1;
425 		for (field = maxval, p = lbuf; field; --field, ++pos) {
426 			if (*pos && output++)
427 				for (i = 0; dcharmb[i] != '\0'; i++)
428 					putchar(dcharmb[i]);
429 			for (;;) {
430 				clen = mbrtowc(&ch, p, lbuf + reallen - p,
431 				    NULL);
432 				if (clen == (size_t)-1 || clen == (size_t)-2) {
433 					warnc(EILSEQ, "%s", fname);
434 					free(mlbuf);
435 					return (1);
436 				}
437 				if (clen == 0)
438 					clen = 1;
439 				p += clen;
440 				if (ch == '\n' || is_delim(ch)) {
441 					/* compress whitespace */
442 					if (wflag && ch != '\n')
443 						while (is_delim(*p))
444 							p++;
445 					break;
446 				}
447 				if (*pos)
448 					for (i = 0; i < (int)clen; i++)
449 						putchar(p[i - clen]);
450 			}
451 			if (ch == '\n')
452 				break;
453 		}
454 		if (ch != '\n') {
455 			if (autostop) {
456 				if (output)
457 					for (i = 0; dcharmb[i] != '\0'; i++)
458 						putchar(dcharmb[i]);
459 				for (; (ch = *p) != '\n'; ++p)
460 					(void)putchar(ch);
461 			} else
462 				for (; (ch = *p) != '\n'; ++p);
463 		}
464 		(void)putchar('\n');
465 	}
466 	free(mlbuf);
467 	return (0);
468 }
469 
470 static void
471 usage(void)
472 {
473 	(void)fprintf(stderr, "%s\n%s\n%s\n",
474 		"usage: cut -b list [-n] [file ...]",
475 		"       cut -c list [file ...]",
476 		"       cut -f list [-s] [-w | -d delim] [file ...]");
477 	exit(1);
478 }
479