📄 arrays.html
字号:
30 31 echo ${arrayZ[@]#f*r} # one two three five five 32 # Applied to all elements of the array. 33 # Matches "four" and removes it. 34 35 # Longest match from front of string(s) 36 echo ${arrayZ[@]##t*e} # one two four five five 37 # Applied to all elements of the array. 38 # Matches "three" and removes it. 39 40 # Shortest match from back of string(s) 41 echo ${arrayZ[@]%h*e} # one two t four five five 42 # Applied to all elements of the array. 43 # Matches "hree" and removes it. 44 45 # Longest match from back of string(s) 46 echo ${arrayZ[@]%%t*e} # one two four five five 47 # Applied to all elements of the array. 48 # Matches "three" and removes it. 49 50 echo "-----------------------" 51 52 # Substring Replacement 53 54 # Replace first occurance of substring with replacement 55 echo ${arrayZ[@]/fiv/XYZ} # one two three four XYZe XYZe 56 # Applied to all elements of the array. 57 58 # Replace all occurances of substring 59 echo ${arrayZ[@]//iv/YY} # one two three four fYYe fYYe 60 # Applied to all elements of the array. 61 62 # Delete all occurances of substring 63 # Not specifing a replacement means 'delete' 64 echo ${arrayZ[@]//fi/} # one two three four ve ve 65 # Applied to all elements of the array. 66 67 # Replace front-end occurances of substring 68 echo ${arrayZ[@]/#fi/XY} # one two three four XYve XYve 69 # Applied to all elements of the array. 70 71 # Replace back-end occurances of substring 72 echo ${arrayZ[@]/%ve/ZZ} # one two three four fiZZ fiZZ 73 # Applied to all elements of the array. 74 75 echo ${arrayZ[@]/%o/XX} # one twXX three four five five 76 # Why? 77 78 echo "-----------------------" 79 80 81 # Before reaching for awk (or anything else) -- 82 # Recall: 83 # $( ... ) is command substitution. 84 # Functions run as a sub-process. 85 # Functions write their output to stdout. 86 # Assignment reads the function's stdout. 87 # The name[@] notation specifies a "for-each" operation. 88 89 newstr() { 90 echo -n "!!!" 91 } 92 93 echo ${arrayZ[@]/%e/$(newstr)} 94 # on!!! two thre!!! four fiv!!! fiv!!! 95 # Q.E.D: The replacement action is an 'assignment.' 96 97 # Accessing the "For-Each" 98 echo ${arrayZ[@]//*/$(newstr optional_arguments)} 99 # Now, if Bash would just pass the matched string as $0 100 #+ to the function being called . . . 101 102 echo 103 104 exit 0</PRE></TD></TR></TABLE><HR></DIV><P><AHREF="commandsub.html#COMMANDSUBREF">Command substitution</A> can construct the individual elements of an array.</P><DIVCLASS="EXAMPLE"><HR><ANAME="SCRIPTARRAY"></A><P><B>Example 26-5. Loading the contents of a script into an array</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 # script-array.sh: Loads this script into an array. 3 # Inspired by an e-mail from Chris Martin (thanks!). 4 5 script_contents=( $(cat "$0") ) # Stores contents of this script ($0) 6 #+ in an array. 7 8 for element in $(seq 0 $((${#script_contents[@]} - 1))) 9 do # ${#script_contents[@]} 10 #+ gives number of elements in the array. 11 # 12 # Question: 13 # Why is seq 0 necessary? 14 # Try changing it to seq 1. 15 echo -n "${script_contents[$element]}" 16 # List each field of this script on a single line. 17 echo -n " -- " # Use " -- " as a field separator. 18 done 19 20 echo 21 22 exit 0 23 24 # Exercise: 25 # -------- 26 # Modify this script so it lists itself 27 #+ in its original format, 28 #+ complete with whitespace, line breaks, etc.</PRE></TD></TR></TABLE><HR></DIV><P>In an array context, some Bash <AHREF="internal.html#BUILTINREF">builtins</A> have a slightly altered meaning. For example, <AHREF="internal.html#UNSETREF">unset</A> deletes array elements, or even an entire array.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX67"></A><P><B>Example 26-6. Some special properties of arrays</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 3 declare -a colors 4 # All subsequent commands in this script will treat 5 #+ the variable "colors" as an array. 6 7 echo "Enter your favorite colors (separated from each other by a space)." 8 9 read -a colors # Enter at least 3 colors to demonstrate features below. 10 # Special option to 'read' command, 11 #+ allowing assignment of elements in an array. 12 13 echo 14 15 element_count=${#colors[@]} 16 # Special syntax to extract number of elements in array. 17 # element_count=${#colors[*]} works also. 18 # 19 # The "@" variable allows word splitting within quotes 20 #+ (extracts variables separated by whitespace). 21 # 22 # This corresponds to the behavior of "$@" and "$*" 23 #+ in positional parameters. 24 25 index=0 26 27 while [ "$index" -lt "$element_count" ] 28 do # List all the elements in the array. 29 echo ${colors[$index]} 30 let "index = $index + 1" 31 done 32 # Each array element listed on a separate line. 33 # If this is not desired, use echo -n "${colors[$index]} " 34 # 35 # Doing it with a "for" loop instead: 36 # for i in "${colors[@]}" 37 # do 38 # echo "$i" 39 # done 40 # (Thanks, S.C.) 41 42 echo 43 44 # Again, list all the elements in the array, but using a more elegant method. 45 echo ${colors[@]} # echo ${colors[*]} also works. 46 47 echo 48 49 # The "unset" command deletes elements of an array, or entire array. 50 unset colors[1] # Remove 2nd element of array. 51 # Same effect as colors[1]= 52 echo ${colors[@]} # List array again, missing 2nd element. 53 54 unset colors # Delete entire array. 55 # unset colors[*] and 56 #+ unset colors[@] also work. 57 echo; echo -n "Colors gone." 58 echo ${colors[@]} # List array again, now empty. 59 60 exit 0</PRE></TD></TR></TABLE><HR></DIV><P>As seen in the previous example, either <BCLASS="COMMAND">${array_name[@]}</B> or <BCLASS="COMMAND">${array_name[*]}</B> refers to <ICLASS="EMPHASIS">all</I> the elements of the array. Similarly, to get a count of the number of elements in an array, use either <BCLASS="COMMAND">${#array_name[@]}</B> or <BCLASS="COMMAND">${#array_name[*]}</B>. <BCLASS="COMMAND">${#array_name}</B> is the length (number of characters) of <BCLASS="COMMAND">${array_name[0]}</B>, the first element of the array.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EMPTYARRAY"></A><P><B>Example 26-7. Of empty arrays and empty elements</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 # empty-array.sh 3 4 # Thanks to Stephane Chazelas for the original example, 5 #+ and to Michael Zick for extending it. 6 7 8 # An empty array is not the same as an array with empty elements. 9 10 array0=( first second third ) 11 array1=( '' ) # "array1" consists of one empty element. 12 array2=( ) # No elements . . . "array2" is empty. 13 14 echo 15 ListArray() 16 { 17 echo 18 echo "Elements in array0: ${array0[@]}" 19 echo "Elements in array1: ${array1[@]}" 20 echo "Elements in array2: ${array2[@]}" 21 echo 22 echo "Length of first element in array0 = ${#array0}" 23 echo "Length of first element in array1 = ${#array1}" 24 echo "Length of first element in array2 = ${#array2}" 25 echo 26 echo "Number of elements in array0 = ${#array0[*]}" # 3 27 echo "Number of elements in array1 = ${#array1[*]}" # 1 (Surprise!) 28 echo "Number of elements in array2 = ${#array2[*]}" # 0 29 } 30 31 # =================================================================== 32 33 ListArray 34 35 # Try extending those arrays. 36 37 # Adding an element to an array. 38 array0=( "${array0[@]}" "new1" ) 39 array1=( "${array1[@]}" "new1" ) 40 array2=( "${array2[@]}" "new1" ) 41 42 ListArray 43 44 # or 45 array0[${#array0[*]}]="new2" 46 array1[${#array1[*]}]="new2" 47 array2[${#array2[*]}]="new2" 48 49 ListArray 50 51 # When extended as above; arrays are 'stacks' 52 # The above is the 'push' 53 # The stack 'height' is: 54 height=${#array2[@]} 55 echo 56 echo "Stack height for array2 = $height" 57 58 # The 'pop' is: 59 unset array2[${#array2[@]}-1] # Arrays are zero-based, 60 height=${#array2[@]} #+ which means first element has index 0. 61 echo 62 echo "POP" 63 echo "New stack height for array2 = $height" 64 65 ListArray 66 67 # List only 2nd and 3rd elements of array0. 68 from=1 # Zero-based numbering. 69 to=2 # 70 array3=( ${array0[@]:1:2} ) 71 echo 72 echo "Elements in array3: ${array3[@]}" 73 74 # Works like a string (array of characters). 75 # Try some other "string" forms. 76 77 # Replacement: 78 array4=( ${array0[@]/second/2nd} ) 79 echo 80 echo "Elements in array4: ${array4[@]}" 81 82 # Replace all matching wildcarded string. 83 array5=( ${array0[@]//new?/old} ) 84 echo 85 echo "Elements in array5: ${array5[@]}" 86 87 # Just when you are getting the feel for this . . . 88 array6=( ${array0[@]#*new} ) 89 echo # This one might surprise you. 90 echo "Elements in array6: ${array6[@]}" 91 92 array7=( ${array0[@]#new1} ) 93 echo # After array6 this should not be a surprise. 94 echo "Elements in array7: ${array7[@]}" 95 96 # Which looks a lot like . . . 97 array8=( ${array0[@]/new1/} ) 98 echo 99 echo "Elements in array8: ${array8[@]}" 100 101 # So what can one say about this? 102 103 # The string operations are performed on 104 #+ each of the elements in var[@] in succession. 105 # Therefore : Bash supports string vector operations 106 #+ if the result is a zero length string, 107 #+ that element disappears in the resulting assignment. 108 109 # Question, are those strings hard or soft quotes? 110 111 zap='new*' 112 array9=( ${array0[@]/$zap/} ) 113 echo 114 echo "Elements in array9: ${array9[@]}" 115 116 # Just when you thought you where still in Kansas . . . 117 array10=( ${array0[@]#$zap} ) 118 echo 119 echo "Elements in array10: ${array10[@]}" 120 121 # Compare array7 with array10. 122 # Compare array8 with array9. 123 124 # Answer: must be soft quotes. 125 126 exit 0</PRE></TD></TR></TABLE><HR></DIV><P>The relationship of <BCLASS="COMMAND">${array_name[@]}</B> and <BCLASS="COMMAND">${array_name[*]}</B> is analogous to that between <AHREF="variables2.html#APPREF">$@ and $*</A>. This powerful array notation has a number of uses.</P><P> <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 # Copying an array. 2 array2=( "${array1[@]}" ) 3 # or 4 array2="${array1[@]}" 5 6 # Adding an element to an array. 7 array=( "${array[@]}" "new element" ) 8 # or 9 array[${#array[*]}]="new element" 10 11 # Thanks, S.C.</PRE></TD></TR></TABLE> </P><DIVCLASS="TIP"><TABLECLASS="TIP"WIDTH="100%"BORDER="0"><TR><TD
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -