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