Reputation: 14138
I have a file in the following format:
somePlane (1,2,3) (1,0,0) (0,0,1) R
awsomePlane (1,0,0) (0,1,0) (0,0,1) B
nicePlane (1,1,1) (2,4,7) (7,1,0) G
I'm trying to sort it [alphabetically according to the first column] and put it into an array while each line is an array element.
But I don't even manage to sort it and have no idea how to put each row into an array element.
I tried the following to sort but it didn't work:
sort -t" " -k1 myfile.txt
What can I do to sort it and insert it into array?
[EDIT] I had a mistake and it seems I was able to sort it, but I still don't know how to insert each line into an array. I used the following command to sort:
sort -t" " -f -k1 myfile.txt
Upvotes: 0
Views: 117
Reputation: 75588
If you're using Bash 4.0 or newer, the best way is to use readarray (synonym for mapfile) with redirection and process substitution, as it doesn't need loops and doesn't risk pathname expansions:
readarray -t ARRAY < <(exec sort -t" " -f -k1 myfile.txt)
Example output:
> for I in "${!ARRAY[@]}"; do echo "$I : ${ARRAY[I]}"; done
0 : awsomePlane (1,0,0) (0,1,0) (0,0,1) B
1 : nicePlane (1,1,1) (2,4,7) (7,1,0) G
2 : somePlane (1,2,3) (1,0,0) (0,0,1) R
Upvotes: 0
Reputation: 274828
You can sort and store the lines into an array as shown below:
# sort and create array
$ IFS=$'\n' arr=( $(sort file.txt) )
# access array elements
$ echo ${arr[0]}
awsomePlane (1,0,0) (0,1,0) (0,0,1) B
$ echo ${arr[1]}
nicePlane (1,1,1) (2,4,7) (7,1,0) G
$ echo ${arr[2]}
somePlane (1,2,3) (1,0,0) (0,0,1) R
Upvotes: 2