I have two arrays with the same number of elements I want to manipulate. They are read from a file into two arrays (odd numbered lines go into array one, even numbered into array 2):
arr1=("1" "1" "3" "2" "4" "7" "7" "7" "1" "2" "3" "3" "3" "3" "7" "5")
arr2=("4" "1" "3" "5" "7" "1" "2" "3" "2" "9" "2" "6" "8" "9" "4" "6")
The data refers to season numbers and episode numbers in the same position across the two arrays. So array 1 (arr1
) is seasons, array 2 (arr2
) is episodes, and they align by element number. So ${arr1[0]}
corresponds to ${arr2[0]}
, etc.
What I am trying to do is sort them so that they are numerically ordered first by season, then by episode. So the original array (with annotations for which item is which element):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
arr1=("1" "1" "3" "2" "4" "7" "7" "7" "1" "2" "3" "3" "3" "3" "7" "5")
arr2=("4" "1" "3" "5" "7" "1" "2" "3" "2" "9" "2" "6" "8" "9" "4" "6")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Becomes:
2 9 1 4 10 12 3 12 13 14 5 16 6 7 8 15
arr1=("1" "1" "1" "2" "2" "3" "3" "3" "3" "3" "4" "5" "7" "7" "7" "7")
arr2=("1" "2" "4" "5" "9" "2" "3" "6" "8" "9" "7" "6" "1" "2" "3" "4")
2 9 1 4 10 12 3 12 13 14 5 16 6 7 8 15
Possible ideas:
- For each item
i
in${arr1[@]}
, write the corresponding element of${arr2[n]}
to a file. The file can then havesort
run on it.
n="0"
for i in "${arr1[@]}"; do
echo "${arr2[${n}]}" >> "${i}.txt"
(( n++ ))
done
But I want to try avoid involving a disk write and sort
if I don't have to.
Sort the data into some kind of an individual array? Each season gets its own array, and then the array can be sorted with something like
sort -n "${season1Arr[@]}"
-- But I don't know how this would be done.Change the way the data is manipulated? I can't change the input file, but I can change the way it's processed. Perhaps instead of reading lines into two arrays based on even/odd line numbers, they could be managed some other way?
I'm trying to keep it as pure-bash as possible for compatibility, but I understand that external programs very may well need to be used. Appreciate any ideas.
sort
if I don't have to." -- no, stop. That's premature optimization. Without first doing it, it's hard to know how big of a performance issue that temporary file or calling outsort
really is. That temporary file isn't even likely to hit disk since the OS caches writes... And, if you really have to start considering performance issues, the first thing to do is to switch from the shell to something else. (Especially since you're running Bash, which isn't fast at all.)