arrays, as a special kind of data structure, have a place in any programming language, and of course bash shells are no exception. This article makes a small summary of the shell array.
Here we only discuss the case of one-dimensional arrays, about multidimensional arrays (in fact, you have to use a one-dimensional array of methods to simulate), not involved. This includes the copying of arrays, computations, deletions, replacements.
1. The Declaration of the array:
1) Array[key]=value # Array[0]=one,array[1]=two
2) declare-a Array # array is treated as an array name
3) array= (value1 value2 value3 ...)
4) array= ([1]=one [2]=two [3]=three ...)
5) array= "One Two Three" # Echo ${array[0|@|*]}, treat the array variable as an array, but the array element has only the string itself
2. Array access:
1) ${array[key]} # ${array[1]}
3. The deletion of the array
1) unset array[1] # Delete the first element in the array
2) unset Array # Delete entire array
4. Calculate the length of the array:
1) ${#array}
2) ${#array [0]} #.${#array [*]}, ${#array [@]}. Note the difference between the same #{array:0}
5. Array extraction
To start from the tail:
array= ([0]=one [1]=two [2]=three [3]=four]
${ARRAY[@]:1} # Two three four, remove all elements after the first element, then ${array[@]:0} represents all elements
${array[@]:0:2} # One Two
${array[@]:1:2} # Two Three
6. Sub-string deletion
[Root@localhost dev]# Echo ${array[@]:0}
One two three four
[Root@localhost dev]# Echo ${array[@] #t *e} # Start the shortest match on the left: ' T*e ', which will match to ' thre '
One two E four
[Root@localhost dev]# echo ${array[@]# #t *e} # Start the longest match on the left, which will match to ' three '
[Root@localhost dev]# array= ([0]=one [1]=two [2]=three [3]=four]]
[Root@localhost dev]# Echo ${array[@]%o} # Start the shortest match from the end of the string
One TW three Four
[Root@localhost dev]# Echo ${array[@]%%o} # start the longest match from the end of the string
One TW three Four
7. Sub-string substitution
[Root@localhost dev]# array= ([0]=one [1]=two [2]=three] [3]=four] [code]
The first one to be matched will be deleted.
[Code] [Root@localhost dev]# Echo ${array[@]/o/m}
Mne TWM Three Fmur
All matches will be deleted.
[Root@localhost dev]# Echo ${array[@]//o/m}
Mne TWM Three Fmur
No replacement substring is specified, then a matching substring is deleted
[Root@localhost dev]# Echo ${array[@]//o/}
NE tw three fur
Replacement string Front terminal string
[Root@localhost dev]# Echo ${array[@]/#o/k}
Kne two Three Four
Replacement string Rear terminal string
[Root@localhost dev]# Echo ${array[@]/%o/k}
One TWK three Four