Awk Field Separators
Brian Rice
rice at dg-rtp.dg.com
Thu Aug 30 03:35:56 AEST 1990
In article <427 at necssd.NEC.COM>, harrison at necssd.NEC.COM (Mark Harrison)
writes:
|> In article <3729 at se-sd.SanDiego.NCR.COM>,
cubbage at se-sd.SanDiego.NCR.COM
|> (Sharon Cubbage) writes:
|>
|> > Does anybody know how to specify more than one field separator in
Awk?
|> > I would like to specify to an Awk program to treat single spaces as
well
|> > as bars as field separators so that a string such as :
|>
|> The new version of Awk (nawk) can do this, but the old version
can't.
If you don't have nawk (you're missing out if you don't!), you can
achieve
the same effect by writing a filter program, like so (this is off the
top of
my head):
#include <stdio.h>
#include <string.h>
#define MY_DELIMITER_CHARS " |\n"
#define MY_OUTPUT_DELIMITER ' '
#define MY_BUFSIZE 256
/* Use the getline() on page 67 of K&R1. */
main()
{
char *strtok();
char buff[MY_BUFSIZE];
char *token;
while (getline(buff,MY_BUFSIZE) != 0) {
token = strtok(buff,MY_DELIMITER_CHARS);
while (token != NULL) {
fputs(token,stdout);
putchar(MY_OUTPUT_DELIMITER);
token = strtok(NULL,MY_DELIMITER_CHARS);
}
putchar('\n');
}
}
Compile and link, then use it like this:
$ echo "1 2 3 4|5|6" | the_above_program | awk '{print $5}'
5
A nice enhancement would be to allow the user to specify a list of input
delimiter characters and the output delimiter character on the command
line (but make sure that newline is an input delimiter, unless you want
to change the code).
--
Brian Rice rice at dg-rtp.dg.com +1 919 248-6328
DG/UX Product Assurance Engineering
Data General Corp., Research Triangle Park, N.C.
More information about the Comp.unix.questions
mailing list