Path: utzoo!utgpu!water!watmath!clyde!att!rutgers!apple!voder!pyramid!prls!philabs!gcm!dc
From: dc@gcm (Dave Caswell)
Newsgroups: comp.sources.wanted
Subject: Re: "cut" needed to run CC
Message-ID: <599@white.gcm>
Date: 18 Sep 88 21:34:31 GMT
References: <990@acornrc.UUCP> <486@poseidon.UUCP> <911@riddle.UUCP>
Reply-To: dc@white.UUCP (Dave Caswell)
Organization: Greenwich Capital Markets, Greenwich, CT
Lines: 97

In article <911@riddle.UUCP> domo@riddle.UUCP (Dominic Dunlop) writes:
>>'cut' selects character-columns (-c) or tab-separated fields (-f) from the
>>named files or stdin, and copies the result to stdout.  e.g.
>>echo "How are you today" | cut -d" " -f1,3
>>will yield "How you". (the -d overrides the separator character).
>>
This is a version someone else wrote, but I believe it works, or is at
lesat a good start.

------------------------------------ cut.c ----------------------------

#include 
#include 
#define BUFSIZ 1024


main(ac, av)

int		ac;
char		*av[];
{
	char	bufin[BUFSIZ];
	char	bufout[BUFSIZ];
	int	include[BUFSIZ];
	int	condense[BUFSIZ + 1];
	int	ndx,
			scan,
			inc;
	int	start,
			num;
	FILE	*fp, *fopen();

	if (ac < 2 || ac > 3 || strncmp(av[1], "-c", 2))
	{
		fprintf(stderr, "ERROR:  format - %s -cstart[-end][,...] [filename]\n", av[0]);
		exit(1);
	}

	for (ndx = 0; ndx < BUFSIZ; ++ndx)
		include[ndx] = 0;

	start = -1;
	for (ndx = 1; ndx < strlen(av[1]) - 1; ++ndx)
	{
		for (scan = ndx + 1; scan < strlen(av[1]) && av[1][scan] != ',' 
			  && av[1][scan] != '-'; ++scan);
		sscanf(&av[1][ndx + 1], "%d", &num);
		if (av[1][scan] == '-')
			start = num;
		else if (scan == strlen(av[1]) || av[1][scan] == ',')
			if (start == -1)
			{
				include[num - 1] = 1;
			}
			else
			{
				if (start < num)
					for (inc = start - 1; inc < num && inc < BUFSIZ; ++inc)
						include[inc] = 1;
				else
					for (inc = num - 1; inc < start && inc < BUFSIZ; ++inc)
						include[inc] = 1;
				start = -1;
			}
		ndx = scan - 1;
	}
	num = 0;
	for (ndx = 0; ndx < BUFSIZ; ++ndx)
		if (include[ndx])
			condense[num++] = ndx;
	condense[num] = -1;
		
	if (ac == 2)
	{
		fp = stdin;
	}
	else if ((fp = fopen(av[2], "r")) == NULL)
	{
		fprintf(stderr, "cut: can't open file %s\n", av[2]);
		exit(1);
	}
	while (fgets(bufin, BUFSIZ, fp) != NULL)
	{
		for (ndx = 0; condense[ndx] >= 0 && condense[ndx] < strlen(bufin) - 1; ++ndx)
			bufout[ndx] = bufin[condense[ndx]];

		if (bufout[ndx - 1] == '\n')
			bufout[ndx - 1] = '\0';
		else
			bufout[ndx] = '\0';

		printf("%s\n", bufout);
	}
}
-- 
Dave Caswell
Greenwich Capital Markets                             uunet!philabs!gcm!dc