[1046] | 1 | # getopt.awk --- do C library getopt(3) function in awk
|
---|
| 2 | #
|
---|
| 3 | # Arnold Robbins, arnold@skeeve.com, Public Domain
|
---|
| 4 | #
|
---|
| 5 | # Initial version: March, 1991
|
---|
| 6 | # Revised: May, 1993
|
---|
| 7 |
|
---|
| 8 | # External variables:
|
---|
| 9 | # Optind -- index in ARGV of first nonoption argument
|
---|
| 10 | # Optarg -- string value of argument to current option
|
---|
| 11 | # Opterr -- if nonzero, print our own diagnostic
|
---|
| 12 | # Optopt -- current option letter
|
---|
| 13 |
|
---|
| 14 | # Returns:
|
---|
| 15 | # -1 at end of options
|
---|
| 16 | # ? for unrecognized option
|
---|
| 17 | # <c> a character representing the current option
|
---|
| 18 |
|
---|
| 19 | # Private Data:
|
---|
| 20 | # _opti -- index in multi-flag option, e.g., -abc
|
---|
| 21 | function getopt(argc, argv, options, thisopt, i)
|
---|
| 22 | {
|
---|
| 23 | if (length(options) == 0) # no options given
|
---|
| 24 | return -1
|
---|
| 25 |
|
---|
| 26 | if (argv[Optind] == "--") { # all done
|
---|
| 27 | Optind++
|
---|
| 28 | _opti = 0
|
---|
| 29 | return -1
|
---|
| 30 | } else if (argv[Optind] !~ /^-[^: \t\n\f\r\v\b]/) {
|
---|
| 31 | _opti = 0
|
---|
| 32 | return -1
|
---|
| 33 | }
|
---|
| 34 | if (_opti == 0)
|
---|
| 35 | _opti = 2
|
---|
| 36 | thisopt = substr(argv[Optind], _opti, 1)
|
---|
| 37 | Optopt = thisopt
|
---|
| 38 | i = index(options, thisopt)
|
---|
| 39 | if (i == 0) {
|
---|
| 40 | if (Opterr)
|
---|
| 41 | printf("%c -- invalid option\n",
|
---|
| 42 | thisopt) > "/dev/stderr"
|
---|
| 43 | if (_opti >= length(argv[Optind])) {
|
---|
| 44 | Optind++
|
---|
| 45 | _opti = 0
|
---|
| 46 | } else
|
---|
| 47 | _opti++
|
---|
| 48 | return "?"
|
---|
| 49 | }
|
---|
| 50 | if (substr(options, i + 1, 1) == ":") {
|
---|
| 51 | # get option argument
|
---|
| 52 | if (length(substr(argv[Optind], _opti + 1)) > 0)
|
---|
| 53 | Optarg = substr(argv[Optind], _opti + 1)
|
---|
| 54 | else
|
---|
| 55 | Optarg = argv[++Optind]
|
---|
| 56 | _opti = 0
|
---|
| 57 | } else
|
---|
| 58 | Optarg = ""
|
---|
| 59 | if (_opti == 0 || _opti >= length(argv[Optind])) {
|
---|
| 60 | Optind++
|
---|
| 61 | _opti = 0
|
---|
| 62 | } else
|
---|
| 63 | _opti++
|
---|
| 64 | return thisopt
|
---|
| 65 | }
|
---|
| 66 | BEGIN {
|
---|
| 67 | Opterr = 1 # default is to diagnose
|
---|
| 68 | Optind = 1 # skip ARGV[0]
|
---|
| 69 |
|
---|
| 70 | # test program
|
---|
| 71 | if (_getopt_test) {
|
---|
| 72 | while ((_go_c = getopt(ARGC, ARGV, "ab:cd")) != -1)
|
---|
| 73 | printf("c = <%c>, optarg = <%s>\n",
|
---|
| 74 | _go_c, Optarg)
|
---|
| 75 | printf("non-option arguments:\n")
|
---|
| 76 | for (; Optind < ARGC; Optind++)
|
---|
| 77 | printf("\tARGV[%d] = <%s>\n",
|
---|
| 78 | Optind, ARGV[Optind])
|
---|
| 79 | }
|
---|
| 80 | }
|
---|