A few days ago I talked to a few colleagues about a problem: How do you pass an array to the inside of awk for processing in a shell script?
No way was found at that time. Two days ago in the QQ group to discuss awk, the conversation inadvertently again. A chance to find a way of thinking, hereby share.
Test environment:
[root]# head-1/etc/redhat-release
Red Hat Enterprise Linux Server release 6.5 (Santiago)
[root]# awk--version | Head-1
GNU Awk 3.1.7
As we all know, it is very easy to pass a generic variable to awk in a shell script, and you can assign a value directly with the-v argument.
str1= "Hello World"
awk-v str2= "$str 1" ' Begin{print str2} '
However, it is not easy to pass an array to awk. Please see the following three trials:
1. Simple array can be assigned first value after split
arr1= (A B C)
awk-v arr2= "${arr1[*]}" ' Begin{split (ARR2,ARR3, ""); Print arr3[2]} '
2. In some cases it is difficult to find the appropriate separator to split, because an array element may contain the character you want to use as a separator, and then you will not get the desired result after the split. So this method is not rigorous enough, especially when we can't predict which characters the array element might contain.
Arr1= (A "B C" D)
awk-v arr2= "${arr1[*]}" ' Begin{split (ARR2,ARR3, ""); Print arr3[2]} '
3. This function can be achieved by using the Export command and the Environ default array of awk
Arr1= (A "B C" D) for
((i=0;i<${#arr1 [*]};i++)); Does
export arr1_m$i= "${arr1[$i]}"
done
awk "begin{ For (i in ENVIRON) if (i~/arr1_m/) print I "=" environ[i]} '
I am here just to demonstrate the function, so I do not have the definition of the export variable name and awk inside the string matching write particularly elegant, you can adjust according to the actual situation (such as adding more restrictions, etc.).
Conclusion: It is technically feasible to pass an array to awk inside the shell script, but it is not recommended to be used in a production environment.