freq

count frequencies of keys in text
git clone git://bvnf.space/freq.git
Log | Files | Refs | README

commit 9945ac4318cdce2206a26064d53b2fd540a4b025
parent 858e2460c2f7b51032552ec2bec8c87e6a687aa4
Author: phoebos <ben@bvnf.space>
Date:   Mon, 21 Mar 2022 20:30:00 +0000

support multiple input files

Diffstat:
MREADME | 11++++++-----
Mfreq.1 | 8++++++--
Mfreq.c | 24++++++++++++------------
3 files changed, 24 insertions(+), 19 deletions(-)

diff --git a/README b/README @@ -4,13 +4,13 @@ NAME freq - count frequencies of keys in text SYNOPSIS - freq [-d delim] [-k key] [file] + freq [-d delim] [-k key] [file ...] DESCRIPTION freq counts the frequencies of each specified field for each line of text - input. For each line, freq checks the field at the specified key and - increments the count for that value of the field. The rest of the line - is ignored. + input from each file. For each line, freq checks the field at the + specified key and increments the count for that value of the field. The + rest of the line is ignored. After checking every line, the counts for each value are printed, in the order in which they are encountered for the first time. The results are @@ -33,7 +33,8 @@ DESCRIPTION OPERANDS file A pathname of an input file. If no file operand is specified, or - if the file operand is `-', then standard input is used. + if the file operand is `-', then standard input is used. If file + does not refer to a valid file, then the operand is ignored. EXIT STATUS The freq utility exits 0 on success, and >0 if an error occurs. diff --git a/freq.1 b/freq.1 @@ -8,10 +8,11 @@ .Nm .Op Fl d Ar delim .Op Fl k Ar key -.Op Ar file +.Op Ar file ... .Sh DESCRIPTION .Nm -counts the frequencies of each specified field for each line of text input. +counts the frequencies of each specified field for each line of text input from each +.Ar file . For each line, .Nm checks the field at the specified @@ -59,6 +60,9 @@ operand is specified, or if the operand is .Sq - , then standard input is used. +If +.Ar file +does not refer to a valid file, then the operand is ignored. .El .Sh EXIT STATUS .Ex -std diff --git a/freq.c b/freq.c @@ -82,29 +82,32 @@ main (int argc, char **argv) { field = atoi(optarg); break; case '?': - fprintf(stderr, "usage: %s [-d delim] [-k fieldnum] [file]\n", argv[0]); + fprintf(stderr, "usage: %s [-d delim] [-k fieldnum] [file...]\n", argv[0]); return 1; } } argc -= optind; - argv += optind; + argv += optind - 1; - FILE *f = stdin; - if (*argv) { + if (argc == 0) + freq(stdin, field); + else while (*++argv) { + FILE *f = stdin; if (strcmp(*argv, "-") != 0) { f = fopen(*argv, "r"); if (f == NULL) { perror(*argv); - return 1; + continue; } } + freq(f, field); + if (f != stdin) + fclose(f); } - freq(f, field); - + print_freqs(); + free_freqs(); - if (f != stdin) - fclose(f); return 0; } @@ -163,7 +166,4 @@ field_found: } free(line); - - print_freqs(); - free_freqs(); }