1

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!

  • Can you give a small example of the input you have and output you want? Also does it really needs to be bash or can an octave script work too? – Presbitero Jan 15 '14 at 19:38
  • I appreciate any help, but let me clarify since I really didn't mean to imply I NEEDED two dimensional arrays. Let's say this is my text file:1 2 3 4 5 next line: 7 10 200 3 I need them stored x(1)=1, y(1)=2....x(2)=7, y(2)=10...and so on. – JClar Jan 15 '14 at 23:13
2

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.

1

Bash supports only one-dimensional arrays, though a little trickery permits simulating multi-dimensional ones.

This document contains an example of a two-dimensional array. http://tldp.org/LDP/abs/html/arrays.html

I wonder if another language may suit your use case more easily. It looks as if you're stretching the limits of what bash can do, whereas Python, Perl or Ruby would handle this task with ease. I guess the tool you'll use for your subsequent "computations" will determine this to a great extent.

-1

sorry I haven’t checked back. The solution was simpler than i thought since the numbers were separated by a space with a return at the end of the lines.

#!/bin/bash
COUNT=1
while read arr1[COUNT] arr2[COUNT] arr3[COUNT] arr4[COUNT] arr5[COUNT]
do
echo "next line"
 echo "${arr1[COUNT]}" 
 echo "${arr2[COUNT]}"
 echo "${arr3[COUNT]}"
 echo "${arr4[COUNT]}"
 echo "${arr5[COUNT]}"
COUNT=$[$COUNT +1]
done < /home/john/testloop.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.