How to cut a variable into array indices?

There is such a typical problem: given the list of values, check to see if they are present in the array.

The awktrick val in arrayworks very well. Therefore, a typical idea is to store all the data in an array and then continue to do validation. For example, this will print all rows in which the value of the first column is present in the array:

awk 'BEGIN {<<initialize the array>>} $1 in array_var' file

However, initializing the array takes some time because it val in arraychecks to see if the index is valin array, and what we usually stored in arrayis a set of values.

This becomes more relevant when providing values ​​from the command line, where those elements that we want to include as array indices. For example, in this basic example (based on my recent answer , which aroused my curiosity):

$ cat file
hello 23
bye 45
adieu 99
$ awk -v values="hello adieu" 'BEGIN {split(values,v); for (i in v) names[v[i]]} $1 in names' file
hello 23
adieu 99
  • split(values,v)cuts a variable valuesinto an arrayv[1]="hello"; v[2]="adieu"
  • for (i in v) names[v[i]]initializes another array names[]with names["hello"]and names["adieu"]with an empty value. So we are ready for
  • $1 in nameswhich checks if the first column is any of the indices in names[].

As you can see, we cut the temporary variable vso that we can later initialize the final and useful variable names[].

, , ?

+4
2

, (- -) (- ) , .

:

BEGIN{split(values,v); for (i in v) names[v[i]]}

, :

$1 in array_var

( , ) - - , , .

+3

, . , .

$ awk -v values="hello adieu" 'FS values FS ~ FS $1 FS' file
hello 23
adieu 99
+2

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


All Articles