Split string directly into array

Suppose I want to pass a string to awk , so that after it is split (by template), the substrings become the indices (and not the values) of the associative array.

Same:

 $ awk -vs="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 

Are there any awkism or gawkism that would allow the direct line s directly decomposed into its components, and do these components become indices in arr ?


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

 awk -vs="1,4,55" 'BEGIN{[arr to arr["1"],arr["5"],arr["55"]} $3 in arr {action}' 
+6
source share
3 answers

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

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

FWIW, if you don't like this approach to execute your last pseudocode:

 awk -vs="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 -vs=",1,4,55," 'index(s,","$3","){action}' 
+3
source

Probably useless and unnecessarily complicated, but I will open the game using while , match and substr :

 $ awk -vs="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 really want to see (if any) some useful solutions. I tried playing with asort etc.

+1
source

Another awkism way

cat file

 1 hi 2 hello 3 bonjour 4 hola 5 konichiwa 

Run it

 awk 'NR==FNR{d[$1]; next}$1 in d' RS="," <(echo "1,2,4") RS="\n" file 

You are getting,

 1 hi 2 hello 4 hola 
+1
source

Source: https://habr.com/ru/post/1014856/


All Articles