Ubuntu – Writing a bash script to read a text file of numbers into arrays, by column, on Ubuntu

12.04bashscripts

I'm trying to write a little bash script on ubuntu 12.04 and have little experience. Odd little problem converting a text file of numbers into arrays. I need all of the first numbers, second, etc into it's own array because I'll be running computations on numbers based on column more than the line it came from. All lines are 5 integers separated by spaces with a return at the end of each line. Is a multidimensional array possible in bash? Thank you!

Best Answer

Here is a script, it will store numbers from text file into two arrays x and y as you wished,

#!/bin/bash

nl=$(cat "$1" | wc -l)
declare -a x
declare -a y
for i in $(seq 1 $nl)
do
    x[i]="$(cat "$1" | awk -v p="$i" '{if(NR==p) print $1}')"
    y[i]="$(cat "$1" | awk -v p="$i" '{if(NR==p) print $2}')"
done
#upto this point all the numbers from first and second column of the file are stored 
#into x and y respectively. Following lines will just print them again for you.
for it in $(seq 1 $nl)
do
    echo "${x[$it]} ${y[$it]}"
done

Do not forget to give the script execution permission.

chmod +x script.sh

Usage

./script.sh numfile.txt

where I am considering you will save the above script as script.sh and your textfile containing numbers is numfile.txt. And both are in same directory.

Related Question