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

📄 string-manipulation.html

📁 Shall高级编程
💻 HTML
📖 第 1 页 / 共 2 页
字号:
	    <TTCLASS="REPLACEABLE"><I>$string</I></TT>.</P></DD><DT>${string##substring}</DT><DD><P>Strips longest match of	    <TTCLASS="REPLACEABLE"><I>$substring</I></TT> from	    <SPANCLASS="emphasis"><ICLASS="EMPHASIS">front</I></SPAN> of	    <TTCLASS="REPLACEABLE"><I>$string</I></TT>.</P><P>  	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;stringZ=abcABC123ABCabc   2&nbsp;#       |----|   3&nbsp;#       |----------|   4&nbsp;   5&nbsp;echo ${stringZ#a*C}      # 123ABCabc   6&nbsp;# Strip out shortest match between 'a' and 'C'.   7&nbsp;   8&nbsp;echo ${stringZ##a*C}     # abc   9&nbsp;# Strip out longest match between 'a' and 'C'.</PRE></TD></TR></TABLE>	  </P></DD><DT>${string%substring}</DT><DD><P>Strips shortest match of	    <TTCLASS="REPLACEABLE"><I>$substring</I></TT> from	    <SPANCLASS="emphasis"><ICLASS="EMPHASIS">back</I></SPAN> of	    <TTCLASS="REPLACEABLE"><I>$string</I></TT>.</P><P>For example:	    <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;# Rename all filenames in $PWD with "TXT" suffix to a "txt" suffix.   2&nbsp;# For example, "file1.TXT" becomes "file1.txt" . . .   3&nbsp;   4&nbsp;SUFF=TXT   5&nbsp;suff=txt   6&nbsp;   7&nbsp;for i in $(ls *.$SUFF)   8&nbsp;do   9&nbsp;  mv -f $i ${i%.$SUFF}.$suff  10&nbsp;  #  Leave unchanged everything *except* the shortest pattern match  11&nbsp;  #+ starting from the right-hand-side of the variable $i . . .  12&nbsp;done ### This could be condensed into a "one-liner" if desired.  13&nbsp;  14&nbsp;# Thank you, Rory Winston.</PRE></TD></TR></TABLE>	  </P></DD><DT>${string%%substring}</DT><DD><P>Strips longest match of	    <TTCLASS="REPLACEABLE"><I>$substring</I></TT> from	    <SPANCLASS="emphasis"><ICLASS="EMPHASIS">back</I></SPAN> of	    <TTCLASS="REPLACEABLE"><I>$string</I></TT>.</P><P>  	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;stringZ=abcABC123ABCabc   2&nbsp;#                    ||   3&nbsp;#        |------------|   4&nbsp;   5&nbsp;echo ${stringZ%b*c}      # abcABC123ABCa   6&nbsp;# Strip out shortest match between 'b' and 'c', from back of $stringZ.   7&nbsp;   8&nbsp;echo ${stringZ%%b*c}     # a   9&nbsp;# Strip out longest match between 'b' and 'c', from back of $stringZ.</PRE></TD></TR></TABLE>	  </P><P>This operator is useful for generating filenames.</P><DIVCLASS="EXAMPLE"><HR><ANAME="CVT"></A><P><B>Example 9-12. Converting graphic file formats, with filename change</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;#  cvt.sh:   3&nbsp;#  Converts all the MacPaint image files in a directory to "pbm" format.   4&nbsp;   5&nbsp;#  Uses the "macptopbm" binary from the "netpbm" package,   6&nbsp;#+ which is maintained by Brian Henderson (bryanh@giraffe-data.com).   7&nbsp;#  Netpbm is a standard part of most Linux distros.   8&nbsp;   9&nbsp;OPERATION=macptopbm  10&nbsp;SUFFIX=pbm          # New filename suffix.   11&nbsp;  12&nbsp;if [ -n "$1" ]  13&nbsp;then  14&nbsp;  directory=$1      # If directory name given as a script argument...  15&nbsp;else  16&nbsp;  directory=$PWD    # Otherwise use current working directory.  17&nbsp;fi    18&nbsp;    19&nbsp;#  Assumes all files in the target directory are MacPaint image files,  20&nbsp;#+ with a ".mac" filename suffix.  21&nbsp;  22&nbsp;for file in $directory/*    # Filename globbing.  23&nbsp;do  24&nbsp;  filename=${file%.*c}      #  Strip ".mac" suffix off filename  25&nbsp;                            #+ ('.*c' matches everything  26&nbsp;			    #+ between '.' and 'c', inclusive).  27&nbsp;  $OPERATION $file &#62; "$filename.$SUFFIX"  28&nbsp;                            # Redirect conversion to new filename.  29&nbsp;  rm -f $file               # Delete original files after converting.     30&nbsp;  echo "$filename.$SUFFIX"  # Log what is happening to stdout.  31&nbsp;done  32&nbsp;  33&nbsp;exit 0  34&nbsp;  35&nbsp;# Exercise:  36&nbsp;# --------  37&nbsp;#  As it stands, this script converts *all* the files in the current  38&nbsp;#+ working directory.  39&nbsp;#  Modify it to work *only* on files with a ".mac" suffix.</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="RA2OGG"></A><P><B>Example 9-13. Converting streaming audio files to	      <ICLASS="FIRSTTERM">ogg</I></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# ra2ogg.sh: Convert streaming audio files (*.ra) to ogg.   3&nbsp;   4&nbsp;# Uses the "mplayer" media player program:   5&nbsp;#      http://www.mplayerhq.hu/homepage   6&nbsp;#      Appropriate codecs may need to be installed for this script to work.   7&nbsp;# Uses the "ogg" library and "oggenc":   8&nbsp;#      http://www.xiph.org/   9&nbsp;  10&nbsp;  11&nbsp;OFILEPREF=${1%%ra}      # Strip off the "ra" suffix.  12&nbsp;OFILESUFF=wav           # Suffix for wav file.  13&nbsp;OUTFILE="$OFILEPREF""$OFILESUFF"  14&nbsp;E_NOARGS=65  15&nbsp;  16&nbsp;if [ -z "$1" ]          # Must specify a filename to convert.  17&nbsp;then  18&nbsp;  echo "Usage: `basename $0` [filename]"  19&nbsp;  exit $E_NOARGS  20&nbsp;fi  21&nbsp;  22&nbsp;  23&nbsp;##########################################################################  24&nbsp;mplayer "$1" -ao pcm:file=$OUTFILE  25&nbsp;oggenc "$OUTFILE"  # Correct file extension automatically added by oggenc.  26&nbsp;##########################################################################  27&nbsp;  28&nbsp;rm "$OUTFILE"      # Delete intermediate *.wav file.  29&nbsp;                   # If you want to keep it, comment out above line.  30&nbsp;  31&nbsp;exit $?  32&nbsp;  33&nbsp;#  Note:  34&nbsp;#  ----  35&nbsp;#  On a Website, simply clicking on a *.ram streaming audio file  36&nbsp;#+ usually only downloads the URL of the actual audio file, the *.ra file.  37&nbsp;#  You can then use "wget" or something similar  38&nbsp;#+ to download the *.ra file itself.  39&nbsp;  40&nbsp;  41&nbsp;#  Exercises:  42&nbsp;#  ---------  43&nbsp;#  As is, this script converts only *.ra filenames.  44&nbsp;#  Add flexibility by permitting use of *.ram and other filenames.  45&nbsp;#  46&nbsp;#  If you're really ambitious, expand the script  47&nbsp;#+ to do automatic downloads and conversions of streaming audio files.  48&nbsp;#  Given a URL, batch download streaming audio files (using "wget")  49&nbsp;#+ and convert them.</PRE></TD></TR></TABLE><HR></DIV><P><ANAME="GETOPTSIMPLE1"></A></P><P>A simple emulation of <AHREF="extmisc.html#GETOPTY">getopt</A>	    using substring extraction constructs.</P><DIVCLASS="EXAMPLE"><HR><ANAME="GETOPTSIMPLE"></A><P><B>Example 9-14. Emulating <ICLASS="FIRSTTERM">getopt</I></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# getopt-simple.sh   3&nbsp;# Author: Chris Morgan   4&nbsp;# Used in the ABS Guide with permission.   5&nbsp;   6&nbsp;   7&nbsp;getopt_simple()   8&nbsp;{   9&nbsp;    echo "getopt_simple()"  10&nbsp;    echo "Parameters are '$*'"  11&nbsp;    until [ -z "$1" ]  12&nbsp;    do  13&nbsp;      echo "Processing parameter of: '$1'"  14&nbsp;      if [ ${1:0:1} = '/' ]  15&nbsp;      then  16&nbsp;          tmp=${1:1}               # Strip off leading '/' . . .  17&nbsp;          parameter=${tmp%%=*}     # Extract name.  18&nbsp;          value=${tmp##*=}         # Extract value.  19&nbsp;          echo "Parameter: '$parameter', value: '$value'"  20&nbsp;          eval $parameter=$value  21&nbsp;      fi  22&nbsp;      shift  23&nbsp;    done  24&nbsp;}  25&nbsp;  26&nbsp;# Pass all options to getopt_simple().  27&nbsp;getopt_simple $*  28&nbsp;  29&nbsp;echo "test is '$test'"  30&nbsp;echo "test2 is '$test2'"  31&nbsp;  32&nbsp;exit 0  33&nbsp;  34&nbsp;---  35&nbsp;  36&nbsp;sh getopt_example.sh /test=value1 /test2=value2  37&nbsp;  38&nbsp;Parameters are '/test=value1 /test2=value2'  39&nbsp;Processing parameter of: '/test=value1'  40&nbsp;Parameter: 'test', value: 'value1'  41&nbsp;Processing parameter of: '/test2=value2'  42&nbsp;Parameter: 'test2', value: 'value2'  43&nbsp;test is 'value1'  44&nbsp;test2 is 'value2'</PRE></TD></TR></TABLE><HR></DIV></DD></DL></DIV><DIVCLASS="VARIABLELIST"><P><B>Substring Replacement</B></P><DL><DT><ANAME="SUBSTRREPL00"></A>${string/substring/replacement}</DT><DD><P>Replace first match of	    <TTCLASS="REPLACEABLE"><I>$substring</I></TT> with	    <TTCLASS="REPLACEABLE"><I>$replacement</I></TT>.</P></DD><DT><ANAME="SUBSTRREPL01"></A>${string//substring/replacement}</DT><DD><P>Replace all matches of	    <TTCLASS="REPLACEABLE"><I>$substring</I></TT> with	    <TTCLASS="REPLACEABLE"><I>$replacement</I></TT>.</P><P>  	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;stringZ=abcABC123ABCabc   2&nbsp;   3&nbsp;echo ${stringZ/abc/xyz}           # xyzABC123ABCabc   4&nbsp;                                  # Replaces first match of 'abc' with 'xyz'.   5&nbsp;   6&nbsp;echo ${stringZ//abc/xyz}          # xyzABC123ABCxyz   7&nbsp;                                  # Replaces all matches of 'abc' with # 'xyz'.</PRE></TD></TR></TABLE>	  </P></DD><DT><ANAME="SUBSTRREPL02"></A>${string/#substring/replacement}</DT><DD><P>If <TTCLASS="REPLACEABLE"><I>$substring</I></TT> matches	    <SPANCLASS="emphasis"><ICLASS="EMPHASIS">front</I></SPAN> end of	    <TTCLASS="REPLACEABLE"><I>$string</I></TT>, substitute	    <TTCLASS="REPLACEABLE"><I>$replacement</I></TT> for	    <TTCLASS="REPLACEABLE"><I>$substring</I></TT>.</P></DD><DT><ANAME="SUBSTRREPL03"></A>${string/%substring/replacement}</DT><DD><P>If <TTCLASS="REPLACEABLE"><I>$substring</I></TT> matches	    <SPANCLASS="emphasis"><ICLASS="EMPHASIS">back</I></SPAN> end of	    <TTCLASS="REPLACEABLE"><I>$string</I></TT>, substitute	    <TTCLASS="REPLACEABLE"><I>$replacement</I></TT> for	    <TTCLASS="REPLACEABLE"><I>$substring</I></TT>.</P><P>            <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;stringZ=abcABC123ABCabc   2&nbsp;   3&nbsp;echo ${stringZ/#abc/XYZ}          # XYZABC123ABCabc   4&nbsp;                                  # Replaces front-end match of 'abc' with 'XYZ'.   5&nbsp;   6&nbsp;echo ${stringZ/%abc/XYZ}          # abcABC123ABCXYZ   7&nbsp;                                  # Replaces back-end match of 'abc' with 'XYZ'.</PRE></TD></TR></TABLE>	  </P></DD></DL></DIV><DIVCLASS="SECT2"><H2CLASS="SECT2"><ANAME="AWKSTRINGMANIP"></A>9.2.1. Manipulating strings using awk</H2><P><ANAME="AWKSTRINGMANIP2"></A></P><P>A Bash script may invoke the string manipulation facilities of	    <AHREF="awk.html#AWKREF">awk</A> as an alternative to using its	    built-in operations.</P><DIVCLASS="EXAMPLE"><HR><ANAME="SUBSTRINGEX"></A><P><B>Example 9-15. Alternate ways of extracting substrings</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# substring-extraction.sh   3&nbsp;   4&nbsp;String=23skidoo1   5&nbsp;#      012345678    Bash   6&nbsp;#      123456789    awk   7&nbsp;# Note different string indexing system:   8&nbsp;# Bash numbers first character of string as '0'.   9&nbsp;# Awk  numbers first character of string as '1'.  10&nbsp;  11&nbsp;echo ${String:2:4} # position 3 (0-1-2), 4 characters long  12&nbsp;                                         # skid  13&nbsp;  14&nbsp;# The awk equivalent of ${string:pos:length} is substr(string,pos,length).  15&nbsp;echo | awk '  16&nbsp;{ print substr("'"${String}"'",3,4)      # skid  17&nbsp;}  18&nbsp;'  19&nbsp;#  Piping an empty "echo" to awk gives it dummy input,  20&nbsp;#+ and thus makes it unnecessary to supply a filename.  21&nbsp;  22&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV></DIV><DIVCLASS="SECT2"><H2CLASS="SECT2"><ANAME="STRFDISC"></A>9.2.2. Further Discussion</H2><P>For more on string manipulation in scripts, refer to <AHREF="parameter-substitution.html">Section 9.3</A> and the       <AHREF="moreadv.html#EXPEXTRSUB">relevant section</A> of the <AHREF="moreadv.html#EXPRREF">expr</A> command listing. For script examples,       see: <OLTYPE="1"><LI><P><AHREF="moreadv.html#EX45">Example 15-9</A></P></LI><LI><P><AHREF="parameter-substitution.html#LENGTH">Example 9-18</A></P></LI><LI><P><AHREF="parameter-substitution.html#PATTMATCHING">Example 9-19</A></P></LI><LI><P><AHREF="parameter-substitution.html#RFE">Example 9-20</A></P></LI><LI><P><AHREF="parameter-substitution.html#VARMATCH">Example 9-22</A></P></LI><LI><P><AHREF="contributed-scripts.html#INSERTIONSORT">Example A-38</A></P></LI></OL>      </P></DIV></DIV><H3CLASS="FOOTNOTES">Notes</H3><TABLEBORDER="0"CLASS="FOOTNOTES"WIDTH="100%"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="5%"><ANAME="FTN.AEN5008"HREF="string-manipulation.html#AEN5008">[1]</A></TD><TDALIGN="LEFT"VALIGN="TOP"WIDTH="95%"><P>This applies to either command-line	       arguments or parameters passed to a <AHREF="functions.html#FUNCTIONREF">function</A>.</P></TD></TR></TABLE><DIVCLASS="NAVFOOTER"><HRALIGN="LEFT"WIDTH="100%"><TABLESUMMARY="Footer navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top"><AHREF="variables2.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="index.html"ACCESSKEY="H">Home</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top"><AHREF="parameter-substitution.html"ACCESSKEY="N">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">Variables Revisited</TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="variables2.html"ACCESSKEY="U">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">Parameter Substitution</TD></TR></TABLE></DIV></BODY></HTML>

⌨️ 快捷键说明

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