3

i've a text file who contains this :

Hello 4
Bye 2
Toto 2

And i want to put the first string of each lines into MyArray1, and the integer into another one MyArray2.

I wrote this, but it doesn't work.

#!/bin/bash

countline=$(awk '{ print $1 }'  test | wc -l)


for ((i=0; i<$countline ;i=i+1))

    do

        MyArray1[$i]=awk '{ print $1 }'  test
done


for ((i=0; i<$countline ;i=i+1))

    do

        MyArray2[$i]=awk '{ print $2 }'  test
done

Please help me.

1
  • Note, this is simpler and faster: countline=$(wc -l < test) Commented Jul 9, 2013 at 20:14

2 Answers 2

4

This would do it:

while read -r f1 f2; do 
    ary1+=("$f1")
    ary2+=("$f2")
done < file

$ printf "%s\n" "${ary1[@]}"
Hello
Bye
Toto

$ printf "%s\n" "${ary2[@]}"
4
2
2

Or you can use cut

arryone=( $(cut -d ' ' -f1 file) )
arrytwo=( $(cut -d ' ' -f2 file) )
Sign up to request clarification or add additional context in comments.

3 Comments

Just to point out how odd bash arrays are, the following works, too: while read -r ary1[i] ary2[i]; do (( i++ )); done (as long as i is 0 or unset to begin with).
Ahh @chepner now that is beautiful! Thank you, I didn't know that.
+1 for a solution that only reads through the file once... and with no extra external processes...
2

Keep it simple:

MyArray1=( $(awk '{ print $1 }' test) )
MyArray2=( $(awk '{ print $2 }' test) )

You don't need to iterate and loop on awk's output and can directly create your arrays as shown above.

Comments

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.