bug-gawk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [bug-gawk] Is there a way to access associative array from the envir


From: Joep van Delft
Subject: Re: [bug-gawk] Is there a way to access associative array from the environment?
Date: Thu, 10 Mar 2016 10:51:53 +0100
User-agent: XS4ALL Webmail



Peng Yu schreef op 2016-03-10 05:31:
Hi, The following command will not access "a" in $MYARRAY. Is there a
way to do so in awk?

declare -A MYARRAY
MYARRAY=([a]=x [b]=y)
awk -e 'BEGIN { print ENVIRON["MYARRAY"]["a"] }'

As others have noted, this is not possible from awk. One can, however,
prepare the contents of an array for awks consumption with the `awk
-e BEGIN{...} -f ...` trick. This preparation should happen from
where you call awk; usually a shell.

How this looks like exactly depends on the shell in use. In zsh, a
rough sketch of a function that spits out the contents of an array
could look like this:

% array2awk() {
    printf "BEGIN{"
    printf $1'["%s"] = "%s"; ' ${(Pkv)1}
    printf "}"
}

Please note: No sanity checking of inputs et cetera.

A test drive:

% declare -A a
% a[aaa]="a a"
% a[b]=bbbbbbbbbb

% array2awk a
BEGIN{a["aaa"] = "a a"; a["b"] = "bbbbbbbbbb"; }

% cat <<EOF >script.awk
BEGIN{ for (k in b) print k, b[k] }
EOF

% awk -e "$(array2awk b)" -f script.awk
a aaa
b b b

Cheers,

Joep



reply via email to

[Prev in Thread] Current Thread [Next in Thread]