简体   繁体   English

如何在UNIX中将awk命令的输出写入数组?

[英]How to write to an array the output of an awk command in UNIX?

I have a flat file which contains the following 我有一个包含以下内容的平面文件

INDIA USA SA NZ AUS ARG GER BRA

so there are eight columns altogether . 所以一共有八列。 Now I want to store the indexes of those columns only which starts with A into an array. 现在,我只想将以A开头的那些列的索引存储到数组中。 For that I tried the following statement 为此,我尝试了以下语句

awk '{for(i=1;i<=NF;i++){if($i~/^A/){set -A newArray $i}}}' testUnix.txt

when I echo the file using 当我使用回显文件时

echo "${newArray[*]}"

it's printing 5 6 but whenever I am trying to get the length of that array 它正在打印5 6,但是每当我尝试获取该数组的长度时

echo ${#newArray[@]}

its length is being shown as 1 only. 其长度仅显示为1。 Should not it be 2 ? 应该不是2吗? I also tried 我也试过

awk '{y = 0;for(i=1;i<=NF;i++){if($i~/^A/){newArray[y] = $i ; y++}}}' testUnix.txt

but also it's producing the same result. 但它也会产生相同的结果。 What am I missing ?Please explain. 我想念什么?请解释。 I intend to get the desired output 2. 我打算获得所需的输出2。

What I would do to have a bash array : 我将如何做一个bash数组:

bash_arr=( $(awk '{for(i=1;i<=NF;i++){if($i~/^A/){print $i}}}' file) )
echo "${bash_arr[@]}"
AUS ARG

And you don't even need awk in reality, bash is capable of doing regex : 而且您甚至不需要awk,bash可以执行regex:

for word in $(<file); do [[ $word =~ ^A ]] && basharr+=( "$word" ); done

No need for awk . 不需要awk You can loop through the elements and check if they start with A : 您可以遍历元素并检查它们是否以A开头:

r="INDIA USA SA NZ AUS ARG GER BRA"
arr=()
for w in $r
do
    [[ $w == A* ]] && arr+=("$w")
done

If you execute it then the arr array contains: 如果执行它,则arr数组包含:

$ for i in  "${arr[@]}"; do echo "$i"; done
AUS
ARG

And to confirm that is has two elements, let's count them: 为了确认其中有两个元素,我们来数一下:

$ echo "${#arr[@]}"
2

What is happening with your aproach? 您的方式是怎么回事?

awk '{for(i=1;i<=NF;i++){if($i~/^A/){set -A newArray $i}}}' testUnix.txt

this says set -A newArray but it is not really defining the variable in bash, because you are in awk. 这说了set -A newArray但实际上并没有在bash中定义变量,因为您在awk中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM