⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 arrays.html

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

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -