StrugglingCoder
StrugglingCoder

Reputation: 5021

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. 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

echo ${#newArray[@]}

its length is being shown as 1 only. Should not it be 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.

Upvotes: 0

Views: 86

Answers (2)

fedorqui
fedorqui

Reputation: 289685

No need for awk. You can loop through the elements and check if they start with 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:

$ 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.

Upvotes: 1

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185073

What I would do to have a bash array :

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 :

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

Upvotes: 1

Related Questions