📄 string-manipulation.html
字号:
<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 stringZ=abcABC123ABCabc 2 # |----| 3 # |----------| 4 5 echo ${stringZ#a*C} # 123ABCabc 6 # Strip out shortest match between 'a' and 'C'. 7 8 echo ${stringZ##a*C} # abc 9 # 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 # Rename all filenames in $PWD with "TXT" suffix to a "txt" suffix. 2 # For example, "file1.TXT" becomes "file1.txt" . . . 3 4 SUFF=TXT 5 suff=txt 6 7 for i in $(ls *.$SUFF) 8 do 9 mv -f $i ${i%.$SUFF}.$suff 10 # Leave unchanged everything *except* the shortest pattern match 11 #+ starting from the right-hand-side of the variable $i . . . 12 done ### This could be condensed into a "one-liner" if desired. 13 14 # 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 stringZ=abcABC123ABCabc 2 # || 3 # |------------| 4 5 echo ${stringZ%b*c} # abcABC123ABCa 6 # Strip out shortest match between 'b' and 'c', from back of $stringZ. 7 8 echo ${stringZ%%b*c} # a 9 # 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 #!/bin/bash 2 # cvt.sh: 3 # Converts all the MacPaint image files in a directory to "pbm" format. 4 5 # Uses the "macptopbm" binary from the "netpbm" package, 6 #+ which is maintained by Brian Henderson (bryanh@giraffe-data.com). 7 # Netpbm is a standard part of most Linux distros. 8 9 OPERATION=macptopbm 10 SUFFIX=pbm # New filename suffix. 11 12 if [ -n "$1" ] 13 then 14 directory=$1 # If directory name given as a script argument... 15 else 16 directory=$PWD # Otherwise use current working directory. 17 fi 18 19 # Assumes all files in the target directory are MacPaint image files, 20 #+ with a ".mac" filename suffix. 21 22 for file in $directory/* # Filename globbing. 23 do 24 filename=${file%.*c} # Strip ".mac" suffix off filename 25 #+ ('.*c' matches everything 26 #+ between '.' and 'c', inclusive). 27 $OPERATION $file > "$filename.$SUFFIX" 28 # Redirect conversion to new filename. 29 rm -f $file # Delete original files after converting. 30 echo "$filename.$SUFFIX" # Log what is happening to stdout. 31 done 32 33 exit 0 34 35 # Exercise: 36 # -------- 37 # As it stands, this script converts *all* the files in the current 38 #+ working directory. 39 # 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 #!/bin/bash 2 # ra2ogg.sh: Convert streaming audio files (*.ra) to ogg. 3 4 # Uses the "mplayer" media player program: 5 # http://www.mplayerhq.hu/homepage 6 # Appropriate codecs may need to be installed for this script to work. 7 # Uses the "ogg" library and "oggenc": 8 # http://www.xiph.org/ 9 10 11 OFILEPREF=${1%%ra} # Strip off the "ra" suffix. 12 OFILESUFF=wav # Suffix for wav file. 13 OUTFILE="$OFILEPREF""$OFILESUFF" 14 E_NOARGS=65 15 16 if [ -z "$1" ] # Must specify a filename to convert. 17 then 18 echo "Usage: `basename $0` [filename]" 19 exit $E_NOARGS 20 fi 21 22 23 ########################################################################## 24 mplayer "$1" -ao pcm:file=$OUTFILE 25 oggenc "$OUTFILE" # Correct file extension automatically added by oggenc. 26 ########################################################################## 27 28 rm "$OUTFILE" # Delete intermediate *.wav file. 29 # If you want to keep it, comment out above line. 30 31 exit $? 32 33 # Note: 34 # ---- 35 # On a Website, simply clicking on a *.ram streaming audio file 36 #+ usually only downloads the URL of the actual audio file, the *.ra file. 37 # You can then use "wget" or something similar 38 #+ to download the *.ra file itself. 39 40 41 # Exercises: 42 # --------- 43 # As is, this script converts only *.ra filenames. 44 # Add flexibility by permitting use of *.ram and other filenames. 45 # 46 # If you're really ambitious, expand the script 47 #+ to do automatic downloads and conversions of streaming audio files. 48 # Given a URL, batch download streaming audio files (using "wget") 49 #+ 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 #!/bin/bash 2 # getopt-simple.sh 3 # Author: Chris Morgan 4 # Used in the ABS Guide with permission. 5 6 7 getopt_simple() 8 { 9 echo "getopt_simple()" 10 echo "Parameters are '$*'" 11 until [ -z "$1" ] 12 do 13 echo "Processing parameter of: '$1'" 14 if [ ${1:0:1} = '/' ] 15 then 16 tmp=${1:1} # Strip off leading '/' . . . 17 parameter=${tmp%%=*} # Extract name. 18 value=${tmp##*=} # Extract value. 19 echo "Parameter: '$parameter', value: '$value'" 20 eval $parameter=$value 21 fi 22 shift 23 done 24 } 25 26 # Pass all options to getopt_simple(). 27 getopt_simple $* 28 29 echo "test is '$test'" 30 echo "test2 is '$test2'" 31 32 exit 0 33 34 --- 35 36 sh getopt_example.sh /test=value1 /test2=value2 37 38 Parameters are '/test=value1 /test2=value2' 39 Processing parameter of: '/test=value1' 40 Parameter: 'test', value: 'value1' 41 Processing parameter of: '/test2=value2' 42 Parameter: 'test2', value: 'value2' 43 test is 'value1' 44 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 stringZ=abcABC123ABCabc 2 3 echo ${stringZ/abc/xyz} # xyzABC123ABCabc 4 # Replaces first match of 'abc' with 'xyz'. 5 6 echo ${stringZ//abc/xyz} # xyzABC123ABCxyz 7 # 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 stringZ=abcABC123ABCabc 2 3 echo ${stringZ/#abc/XYZ} # XYZABC123ABCabc 4 # Replaces front-end match of 'abc' with 'XYZ'. 5 6 echo ${stringZ/%abc/XYZ} # abcABC123ABCXYZ 7 # 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 #!/bin/bash 2 # substring-extraction.sh 3 4 String=23skidoo1 5 # 012345678 Bash 6 # 123456789 awk 7 # Note different string indexing system: 8 # Bash numbers first character of string as '0'. 9 # Awk numbers first character of string as '1'. 10 11 echo ${String:2:4} # position 3 (0-1-2), 4 characters long 12 # skid 13 14 # The awk equivalent of ${string:pos:length} is substr(string,pos,length). 15 echo | awk ' 16 { print substr("'"${String}"'",3,4) # skid 17 } 18 ' 19 # Piping an empty "echo" to awk gives it dummy input, 20 #+ and thus makes it unnecessary to supply a filename. 21 22 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 + -