Starting with a simple text file:
$ cat list.txt
fork
knife
spoon
And build an array out of that:
$ myarray=($(cat list.txt))
We can get the number of elements in our bash array with
$ echo ${#myarray[@]}
3
You can print the whole array with
$ echo ${myarray[@]}
fork knife spoon
Or you can use a for loop to walk the bash array and print each element:
$ for i in ${myarray[@]}; do echo $i; done
fork
knife
spoon
You can also do a for loop but use array indexes instead of each element:
$ for i in ${!myarray[@]}; do echo $i; done
0
1
2
Putting it together:
$ for i in ${!myarray[@]}; do echo "$i -> ${myarray[i]}"; done
0 -> fork
1 -> knife
2 -> spoon
We can remove an array element with:
$ for i in ${!myarray[@]}; do if [ "${myarray[i]}" = "knife" ]; then unset myarray[i]; fi; done
Which leaves us with:
$ for i in ${!myarray[@]}; do echo "$i -> ${myarray[i]}"; done
0 -> fork
2 -> spoon
Unfortunately, there are no two or three dimensional arrays in bash. But you can usually get away with parsing the contents of a regular, one dimension array.
No comments:
Post a Comment