Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk command result into array

Tags:

arrays

linux

bash

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.

like image 446
Adeel ASIF Avatar asked Sep 01 '26 15:09

Adeel ASIF


1 Answers

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) )
like image 179
jaypal singh Avatar answered Sep 04 '26 04:09

jaypal singh