This article introduces the array-related knowledge in linxu shell and provides many examples for reference, including array copying, calculation, deletion, and replacement, it is a rare article to learn shell arrays.
Array declaration:
1) array [key] = value # array [0] = one, array [1] = two
2) declare-a array # array is treated as the array name
3) array = (value1 value2 value3 ...)
4) array = ([1] = one [2] = two [3] = three ...)
5) array = "one two three" # echo $ {array [0 | @ | *]}. The array variable is treated as an array, but the array element only contains the string itself.
Array access:
1) $ {array [key] }#$ {array [1]}
Delete An Array
1) unset array [1] # Delete the first element in the array
2) unset array # Delete the entire array
Calculate the length of the array:
Copy codeThe Code is as follows: $ {# array}
$ {# Array [0]} # Same as above. $ {# Array [*]} and $ {# array [@]}. Note the difference between # {array: 0} and # {array: 0 }.
Array Extraction
Extract from the tail:Copy codeThe Code is as follows: array = ([0] = one [1] = two [2] = three [3] = four)
$ {Array [@]: 1} # two three four. After removing all elements from the first element, $ {array [@]: 0} indicates all elements.
$ {Array [@]: 0: 2} # one two
$ {Array [@]: 1: 2} # two three
Delete a substringCopy codeThe Code is 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 matches "thre"
One two e four
[Root @ localhost dev] # echo $ {array [@] # t * e} # The longest match from the left, which matches "three"
[Root @ localhost dev] # array = ([0] = one [1] = two [2] = three [3] = four)
[Root @ localhost dev] # echo $ {array [@] % o} # minimum matching from the end of a string
One tw three four
[Root @ localhost dev] # echo $ {array [@] % o} # longest match starting from the end of the string
One tw three four
Substring replacement
Copy codeThe Code is as follows: [root @ localhost dev] # array = ([0] = one [1] = two [2] = three [3] = four)
The first matched one will be deleted.
[Root @ localhost dev] # echo $ {array [@]/o/m}
Mne twm three fmur
All matched items will be deleted.
[Root @ localhost dev] # echo $ {array [@] // o/m}
Mne twm three fmur
If the child string is not specified, the matched child string is deleted.
[Root @ localhost dev] # echo $ {array [@] // o /}
Ne tw three fur
Replace the first terminal string
[Root @ localhost dev] # echo $ {array [@]/# o/k}
Kne two three four
Terminal string after replacement string
[Root @ localhost dev] # echo $ {array [@]/% o/k}
One twk three four