This article introduces the Linxu shell of the relevant knowledge of the array, and a lot of examples for reference, including the copy of the array, calculation, deletion, replacement, etc., is to learn the shell array of rare good articles.
The declaration of an 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
Array Access:
1) ${array[key]} # ${array[1]}
The deletion of an array
1) unset array[1] # Delete the first element in the array
2) unset Array # Delete entire array
To calculate the length of an array:
Copy Code code as follows:
${#array}
${#array [0]} #同上. ${#array [*]}, ${#array [@]}. Note the difference between the same #{array:0}
Extraction of arrays
To start from the tail:
Copy Code code as follows:
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
Sub-string deletion
Copy Code code as follows:
[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
Child string substitution
Copy Code code as follows:
[Root@localhost dev]# array= ([0]=one [1]=two [2]=three [3]=four]]
The first one to be matched will be deleted.
[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