0

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.

2
  • 1
    The newArray in awk and bash are two different entities. So when you type echo "${newArray[*]}" its the value of bash array you are getting Commented Nov 18, 2014 at 13:57
  • 1
    Have to say - I think this is where things like Perl or Python start to come into their own. Commented Nov 18, 2014 at 14:06

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

it's length is still 1 :(
??? What's the problem ? You have the 2 searched elements. Dunno what's wrong. The index start @ zero !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.