I am new to Bash scripting and presently find myself dealing with a small problem in working with for loops, arrays and variable assignment/substitution which I do not know how to solve. Since I am quite literally new, I do not even know how to look this up. Although anyone could say this, I stress that this isn't homework or anything of the sort - I just need to reorganize a humongous amount of data for later processing and thought I'd do it in a somewhat smart way while learning some Bash.
Background: I have a directory which itself contains three subdirectories - Folder1, Folder2, Folder3. Each subdirectory has one data.txt file. Each data.txt file features three columns with a fixed number of rows.
Goal: I want to launch a Bash script from the main directory which iterates over the subdirectories and carries out the following:
- it enters and accesses the data.txt;
- it reads each column into the corresponding array
arr1
,arr2
,arr3
(these are emptied/reset when entering the next subdirectory); - it reads
arr2[0]
intoearr1
,arr2[1]
intoearr2
, ...,arr2[j-1]
intoearr$j
. A similar structure is followed for the data inarr3
. Theearr$j
keep the data from past iterations and constitute my desired output arrays. With every sweep of a new directory, data are appended to these.
It sounds overly complicated - but that's the structure of the data I have to work with. For the most part, I have figured out a working solution (granted, probably not the best one).
Problem:
For some reason I am not able to identify, I am getting all kinds of errors with every attempt at appending as earr$j+=(${arr2[j-1]})
(and all sorts of variations I have tried out) in a loop over j
. Below is the snippet giving me trouble. I would appreciate if someone could point out how what the problem is and, if possible, provide a working example of a solution.
The for-loop in question:
for j in $(seq 1 $number_of_lists); do echo "(${arr2[j-1]})"; earr$j+=(${arr2[j-1]}); echo "(${arr3[j-1]})"; done
In particular, I have trouble with the earr$j+=(${arr2[j-1]})
part. This is my error output:
./next.sh: line 33: syntax error near unexpected token "${arr2[j-1]}''
and ./next.sh: line 33: earr$j+=('${arr2[j-1]}')
.
Thank you in advance for any suggestions.