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

📄 arrays.html

📁 一本完整的描述Unix Shell 编程的工具书的所有范例
💻 HTML
📖 第 1 页 / 共 5 页
字号:
  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. 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&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;done  32&nbsp;# Each array element listed on a separate line.  33&nbsp;# If this is not desired, use  echo -n "${colors[$index]} "  34&nbsp;#  35&nbsp;# Doing it with a "for" loop instead:  36&nbsp;#   for i in "${colors[@]}"  37&nbsp;#   do  38&nbsp;#     echo "$i"  39&nbsp;#   done  40&nbsp;# (Thanks, S.C.)  41&nbsp;  42&nbsp;echo  43&nbsp;  44&nbsp;# Again, list all the elements in the array, but using a more elegant method.  45&nbsp;  echo ${colors[@]}          # echo ${colors[*]} also works.  46&nbsp;  47&nbsp;echo  48&nbsp;  49&nbsp;# The "unset" command deletes elements of an array, or entire array.  50&nbsp;unset colors[1]              # Remove 2nd element of array.  51&nbsp;                             # Same effect as   colors[1]=  52&nbsp;echo  ${colors[@]}           # List array again, missing 2nd element.  53&nbsp;  54&nbsp;unset colors                 # Delete entire array.  55&nbsp;                             #  unset colors[*] and  56&nbsp;                             #+ unset colors[@] also work.  57&nbsp;echo; echo -n "Colors gone."			     58&nbsp;echo ${colors[@]}            # List array again, now empty.  59&nbsp;  60&nbsp;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&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 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;  14&nbsp;echo  15&nbsp;ListArray()  16&nbsp;{  17&nbsp;echo  18&nbsp;echo "Elements in array0:  ${array0[@]}"  19&nbsp;echo "Elements in array1:  ${array1[@]}"  20&nbsp;echo "Elements in array2:  ${array2[@]}"  21&nbsp;echo  22&nbsp;echo "Length of first element in array0 = ${#array0}"  23&nbsp;echo "Length of first element in array1 = ${#array1}"  24&nbsp;echo "Length of first element in array2 = ${#array2}"  25&nbsp;echo  26&nbsp;echo "Number of elements in array0 = ${#array0[*]}"  # 3  27&nbsp;echo "Number of elements in array1 = ${#array1[*]}"  # 1  (Surprise!)  28&nbsp;echo "Number of elements in array2 = ${#array2[*]}"  # 0  29&nbsp;}  30&nbsp;  31&nbsp;# ===================================================================  32&nbsp;  33&nbsp;ListArray  34&nbsp;  35&nbsp;# Try extending those arrays.  36&nbsp;  37&nbsp;# Adding an element to an array.  38&nbsp;array0=( "${array0[@]}" "new1" )  39&nbsp;array1=( "${array1[@]}" "new1" )  40&nbsp;array2=( "${array2[@]}" "new1" )  41&nbsp;  42&nbsp;ListArray  43&nbsp;  44&nbsp;# or  45&nbsp;array0[${#array0[*]}]="new2"  46&nbsp;array1[${#array1[*]}]="new2"  47&nbsp;array2[${#array2[*]}]="new2"  48&nbsp;  49&nbsp;ListArray  50&nbsp;  51&nbsp;# When extended as above; arrays are 'stacks'  52&nbsp;# The above is the 'push'  53&nbsp;# The stack 'height' is:  54&nbsp;height=${#array2[@]}  55&nbsp;echo  56&nbsp;echo "Stack height for array2 = $height"  57&nbsp;  58&nbsp;# The 'pop' is:  59&nbsp;unset array2[${#array2[@]}-1]	#  Arrays are zero-based,  60&nbsp;height=${#array2[@]}            #+ which means first element has index 0.  61&nbsp;echo  62&nbsp;echo "POP"  63&nbsp;echo "New stack height for array2 = $height"  64&nbsp;  65&nbsp;ListArray  66&nbsp;  67&nbsp;# List only 2nd and 3rd elements of array0.  68&nbsp;from=1		# Zero-based numbering.  69&nbsp;to=2		#  70&nbsp;array3=( ${array0[@]:1:2} )  71&nbsp;echo  72&nbsp;echo "Elements in array3:  ${array3[@]}"  73&nbsp;  74&nbsp;# Works like a string (array of characters).  75&nbsp;# Try some other "string" forms.  76&nbsp;  77&nbsp;# Replacement:  78&nbsp;array4=( ${array0[@]/second/2nd} )  79&nbsp;echo  80&nbsp;echo "Elements in array4:  ${array4[@]}"  81&nbsp;  82&nbsp;# Replace all matching wildcarded string.  83&nbsp;array5=( ${array0[@]//new?/old} )  84&nbsp;echo  85&nbsp;echo "Elements in array5:  ${array5[@]}"  86&nbsp;  87&nbsp;# Just when you are getting the feel for this . . .  88&nbsp;array6=( ${array0[@]#*new} )  89&nbsp;echo # This one might surprise you.  90&nbsp;echo "Elements in array6:  ${array6[@]}"  91&nbsp;  92&nbsp;array7=( ${array0[@]#new1} )  93&nbsp;echo # After array6 this should not be a surprise.  94&nbsp;echo "Elements in array7:  ${array7[@]}"  95&nbsp;  96&nbsp;# Which looks a lot like . . .  97&nbsp;array8=( ${array0[@]/new1/} )  98&nbsp;echo  99&nbsp;echo "Elements in array8:  ${array8[@]}" 100&nbsp; 101&nbsp;#  So what can one say about this? 102&nbsp; 103&nbsp;#  The string operations are performed on 104&nbsp;#+ each of the elements in var[@] in succession. 105&nbsp;#  Therefore : Bash supports string vector operations 106&nbsp;#+ if the result is a zero length string, 107&nbsp;#+ that element disappears in the resulting assignment. 108&nbsp; 109&nbsp;#  Question, are those strings hard or soft quotes? 110&nbsp; 111&nbsp;zap='new*' 112&nbsp;array9=( ${array0[@]/$zap/} ) 113&nbsp;echo 114&nbsp;echo "Elements in array9:  ${array9[@]}" 115&nbsp; 116&nbsp;# Just when you thought you where still in Kansas . . . 117&nbsp;array10=( ${array0[@]#$zap} ) 118&nbsp;echo 119&nbsp;echo "Elements in array10:  ${array10[@]}" 120&nbsp; 121&nbsp;# Compare array7 with array10. 122&nbsp;# Compare array8 with array9. 123&nbsp; 124&nbsp;# Answer: must be soft quotes. 125&nbsp; 126&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>      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;# Copying an array.   2&nbsp;array2=( "${array1[@]}" )   3&nbsp;# or   4&nbsp;array2="${array1[@]}"   5&nbsp;   6&nbsp;# Adding an element to an array.   7&nbsp;array=( "${array[@]}" "new element" )   8&nbsp;# or   9&nbsp;array[${#array[*]}]="new element"  10&nbsp;  11&nbsp;# 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 + -