Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string directly into array

Tags:

arrays

awk

gawk

Suppose I want to pass a string to awk so that once I split it (on a pattern) the substrings become the indexes (not the values) of an associative array.

Like so:

$ awk -v s="A:B:F:G" 'BEGIN{ # easy, but can these steps be combined?
                            split(s,temp,":")  # temp[1]="A",temp[2]="B"...
                            for (e in temp) arr[temp[e]] #arr["A"], arr["B"]...
                            for (e in arr) print e 
                            }'
A
B
F
G

Is there a awkism or gawkism that would allow the string s to be directly split into its components with those components becoming the index entries in arr?


The reason is (bigger picture) is I want something like this (pseudo awk):

awk -v s="1,4,55" 'BEGIN{[arr to arr["1"],arr["5"],arr["55"]} $3 in arr {action}'
like image 800
dawg Avatar asked Feb 09 '17 20:02

dawg


2 Answers

No, there is no better way to map separated substrings to array indices than:

split(str,tmp); for (i in tmp) arr[tmp[i]]

FWIW if you don't like that approach for doing what your final pseudo-code does:

awk -v s="1,4,55" 'BEGIN{split(s,tmp,/,/); for (i in tmp) arr[tmp[i]]} $3 in arr{action}'

then another way to get the same behavior is

awk -v s=",1,4,55," 'index(s,","$3","){action}'
like image 120
Ed Morton Avatar answered Sep 28 '22 18:09

Ed Morton


Probably useless and unnecessarily complex but I'll open the game with while, match and substr:

$ awk -v s="A:B:F:G" '
BEGIN {
    while(match(s,/[^:]+/)) {
        a[substr(s,RSTART,RLENGTH)]
        s=substr(s,RSTART+RLENGTH)
    }
    for(i in a)
        print i
}'
A
B
F
G

I'm eager to see (if there are) some useful solutions. I tried playing around with asorts and such.

like image 21
James Brown Avatar answered Sep 28 '22 19:09

James Brown