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