简体   繁体   中英

AWK how to initialize a variable with multiple number of fields to print

I'm writing a SHELL script that will call an AWK script file printing specific fields based on the options specified by the user from the .sh script

EXAMPLE

-N=field with a list of Names               ==> is the filed number 2
-A=field with a list of Addresses           ==> is the filed number 4
-P=field with a list of Prices              ==> is the field number 6
-D=field with a list of Dates               ==> is the field number 10


./SHELLSCRIPT.sh -N -A -P -D

NAMES,ADDRESSES,PRICES,DATES
NAMES,ADDRESSES,PRICES,DATES
NAMES,ADDRESSES,PRICES,DATES

EXAMPLE

./SHELLSCRIPT.sh -N -D

NAMES,DATES
NAMES,DATES
NAMES,DATES

I'm trying to initialize a variable inside AWK using the -v option passing the number of fields but I'm having some difficulties on printing it...

here is the AWK script:

#!/usr/bin/awk -f
BEGIN {
        FS="\",\"" ;
        -v test=2,4,6,10
        for (i in test)
        print $test[i];
        }

AWK script must exclude some field/s when the user doesn't specify some option/s in the shell script

Thanks in advance for your attention and support.

-v is an awk ARGUMENT, not a language construct. It's something you specify on the awk command line, like -F . Nevere use a shebang to invoke awk from a script as it just takes away from available functionality. Instead of what you had:

#!/usr/bin/awk -f
BEGIN {...}

you'd do this:

/usr/bin/awk '
BEGIN {...}
' "$@"

which then lets you use awk args, access shell positional parameters, exported variables, etc. as you like, eg:

/usr/bin/awk -v test='2,4,6,10' '
BEGIN {...}
' "$@"

Now, to address your actual problem you'd write:

/usr/bin/awk -F'"," -v test='2,4,6,10' '
BEGIN {
    split(test,array1,/,/)
    for (i in array1)
        array2[array1[i]]
}
{
    print "array1:"
    for (i=1; i in array1; i++) {
        print i, $(array1[i])
    }
    print "array2:"
    for (i in array2) {
        print i, $i
    }
}
' "$@"

array1 would be what you use when you do care about the order in which the fields are output, array2 would be when you don't care about the order.

Maybe this wil help:

awk -v bozo=12 -v brains=99 'BEGIN{print bozo,brains}' /dev/null
12 99

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM