📄 moreadv.html
字号:
16 echo >>logfile 17 echo >>logfile 18 19 exit 0 20 21 # Note: 22 # ---- 23 # As Frank Wang points out, 24 #+ unmatched quotes (either single or double quotes) in the source file 25 #+ may give xargs indigestion. 26 # 27 # He suggests the following substitution for line 15: 28 # tail -$LINES /var/log/messages | tr -d "\"'" | xargs | fmt -s >>logfile 29 30 31 32 # Exercise: 33 # -------- 34 # Modify this script to track changes in /var/log/messages at intervals 35 #+ of 20 minutes. 36 # Hint: Use the "watch" command. </PRE></TD></TR></TABLE><HR></DIV><P><AHREF="moreadv.html#CURLYBRACKETSREF">As in <BCLASS="COMMAND">find</B></A>, a curly bracket pair serves as a placeholder for replacement text.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX42"></A><P><B>Example 12-6. Copying files in current directory to another</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 # copydir.sh 3 4 # Copy (verbose) all files in current directory ($PWD) 5 #+ to directory specified on command line. 6 7 E_NOARGS=65 8 9 if [ -z "$1" ] # Exit if no argument given. 10 then 11 echo "Usage: `basename $0` directory-to-copy-to" 12 exit $E_NOARGS 13 fi 14 15 ls . | xargs -i -t cp ./{} $1 16 # ^^ ^^ ^^ 17 # -t is "verbose" (output command line to stderr) option. 18 # -i is "replace strings" option. 19 # {} is a placeholder for output text. 20 # This is similar to the use of a curly bracket pair in "find." 21 # 22 # List the files in current directory (ls .), 23 #+ pass the output of "ls" as arguments to "xargs" (-i -t options), 24 #+ then copy (cp) these arguments ({}) to new directory ($1). 25 # 26 # The net result is the exact equivalent of 27 #+ cp * $1 28 #+ unless any of the filenames has embedded "whitespace" characters. 29 30 exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="KILLBYNAME"></A><P><B>Example 12-7. Killing processes by name</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 # kill-byname.sh: Killing processes by name. 3 # Compare this script with kill-process.sh. 4 5 # For instance, 6 #+ try "./kill-byname.sh xterm" -- 7 #+ and watch all the xterms on your desktop disappear. 8 9 # Warning: 10 # ------- 11 # This is a fairly dangerous script. 12 # Running it carelessly (especially as root) 13 #+ can cause data loss and other undesirable effects. 14 15 E_BADARGS=66 16 17 if test -z "$1" # No command line arg supplied? 18 then 19 echo "Usage: `basename $0` Process(es)_to_kill" 20 exit $E_BADARGS 21 fi 22 23 24 PROCESS_NAME="$1" 25 ps ax | grep "$PROCESS_NAME" | awk '{print $1}' | xargs -i kill {} 2&>/dev/null 26 # ^^ ^^ 27 28 # ----------------------------------------------------------- 29 # Notes: 30 # -i is the "replace strings" option to xargs. 31 # The curly brackets are the placeholder for the replacement. 32 # 2&>/dev/null suppresses unwanted error messages. 33 # ----------------------------------------------------------- 34 35 exit $?</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="WF2"></A><P><B>Example 12-8. <BCLASS="COMMAND">Word frequency analysis</B> using <BCLASS="COMMAND">xargs</B></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 # wf2.sh: Crude word frequency analysis on a text file. 3 4 # Uses 'xargs' to decompose lines of text into single words. 5 # Compare this example to the "wf.sh" script later on. 6 7 8 # Check for input file on command line. 9 ARGS=1 10 E_BADARGS=65 11 E_NOFILE=66 12 13 if [ $# -ne "$ARGS" ] 14 # Correct number of arguments passed to script? 15 then 16 echo "Usage: `basename $0` filename" 17 exit $E_BADARGS 18 fi 19 20 if [ ! -f "$1" ] # Check if file exists. 21 then 22 echo "File \"$1\" does not exist." 23 exit $E_NOFILE 24 fi 25 26 27 28 ######################################################## 29 cat "$1" | xargs -n1 | \ 30 # List the file, one word per line. 31 tr A-Z a-z | \ 32 # Shift characters to lowercase. 33 sed -e 's/\.//g' -e 's/\,//g' -e 's/ /\ 34 /g' | \ 35 # Filter out periods and commas, and 36 #+ change space between words to linefeed, 37 sort | uniq -c | sort -nr 38 # Finally prefix occurrence count and sort numerically. 39 ######################################################## 40 41 # This does the same job as the "wf.sh" example, 42 #+ but a bit more ponderously, and it runs more slowly (why?). 43 44 exit 0</PRE></TD></TR></TABLE><HR></DIV></DD><DT><ANAME="EXPRREF"></A><TTCLASS="USERINPUT"><B>expr</B></TT></DT><DD><P>All-purpose expression evaluator: Concatenates and evaluates the arguments according to the operation given (arguments must be separated by spaces). Operations may be arithmetic, comparison, string, or logical.</P><DIVCLASS="VARIABLELIST"><DL><DT><TTCLASS="USERINPUT"><B>expr 3 + 5</B></TT></DT><DD><P>returns <TTCLASS="LITERAL">8</TT></P></DD><DT><TTCLASS="USERINPUT"><B>expr 5 % 3</B></TT></DT><DD><P>returns 2</P></DD><DT><TTCLASS="USERINPUT"><B>expr 1 / 0</B></TT></DT><DD><P>returns the error message, <ICLASS="EMPHASIS">expr: division by zero</I></P><P>Illegal arithmetic operations not allowed.</P></DD><DT><TTCLASS="USERINPUT"><B>expr 5 \* 3</B></TT></DT><DD><P>returns 15</P><P>The multiplication operator must be escaped when used in an arithmetic expression with <BCLASS="COMMAND">expr</B>.</P></DD><DT><TTCLASS="USERINPUT"><B>y=`expr $y + 1`</B></TT></DT><DD><P>Increment a variable, with the same effect as <TTCLASS="USERINPUT"><B>let y=y+1</B></TT> and <TTCLASS="USERINPUT"><B>y=$(($y+1))</B></TT>. This is an example of <AHREF="arithexp.html#ARITHEXPREF">arithmetic expansion</A>.</P></DD><DT><ANAME="EXPEXTRSUB"></A><TTCLASS="USERINPUT"><B>z=`expr substr $string $position $length`</B></TT></DT><DD><P>Extract substring of $length characters, starting at $position.</P></DD></DL></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="EX45"></A><P><B>Example 12-9. Using <BCLASS="COMMAND">expr</B></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 3 # Demonstrating some of the uses of 'expr' 4 # ======================================= 5 6 echo 7 8 # Arithmetic Operators 9 # ---------- --------- 10 11 echo "Arithmetic Operators" 12 echo 13 a=`expr 5 + 3` 14 echo "5 + 3 = $a" 15 16 a=`expr $a + 1` 17 echo 18 echo "a + 1 = $a" 19 echo "(incrementing a variable)" 20 21 a=`expr 5 % 3` 22 # modulo 23 echo 24 echo "5 mod 3 = $a" 25 26 echo 27 echo 28 29 # Logical Operators 30 # ------- --------- 31 32 # Returns 1 if true, 0 if false, 33 #+ opposite of normal Bash convention. 34 35 echo "Logical Operators" 36 echo 37 38 x=24 39 y=25 40 b=`expr $x = $y` # Test equality. 41 echo "b = $b" # 0 ( $x -ne $y ) 42 echo 43 44 a=3 45 b=`expr $a \> 10` 46 echo 'b=`expr $a \> 10`, therefore...' 47 echo "If a > 10, b = 0 (false)" 48 echo "b = $b" # 0 ( 3 ! -gt 10 ) 49 echo 50 51 b=`expr $a \< 10` 52 echo "If a < 10, b = 1 (true)" 53 echo "b = $b" # 1 ( 3 -lt 10 ) 54 echo 55 # Note escaping of operators. 56 57 b=`expr $a \<= 3` 58 echo "If a <= 3, b = 1 (true)" 59 echo "b = $b" # 1 ( 3 -le 3 ) 60 # There is also a "\>=" operator (greater than or equal to). 61 62 63 echo 64 echo 65 66 67 68 # String Operators 69 # ------ --------- 70 71 echo "String Operators" 72 echo 73 74 a=1234zipper43231 75 echo "The string being operated upon is \"$a\"." 76 77 # length: length of string 78 b=`expr length $a` 79 echo "Length of \"$a\" is $b." 80 81 # index: position of first character in substring 82 # that matches a character in string 83 b=`expr index $a 23` 84 echo "Numerical position of first \"2\" in \"$a\" is \"$b\"." 85 86 # substr: extract substring, starting position & length specified 87 b=`expr substr $a 2 6` 88 echo "Substring of \"$a\", starting at position 2,\ 89 and 6 chars long is \"$b\"." 90 91 92 # The default behavior of the 'match' operations is to 93 #+ search for the specified match at the ***beginning*** of the string. 94 # 95 # uses Regular Expressions 96 b=`expr match "$a" '[0-9]*'` # Numerical count. 97 echo Number of digits at the beginning of \"$a\" is $b. 98 b=`expr match "$a" '\([0-9]*\)'` # Note that escaped parentheses 99 # == == + trigger substring match. 100 echo "The digits at the beginning of \"$a\" are \"$b\"." 101 102 echo 103 104 exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="IMPORTANT"><TABLECLASS="IMPORTANT"WIDTH="90%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/important.png"HSPACE="5"ALT="Important"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>The <AHREF="special-chars.html#NULLREF">:</A> operator can substitute for <BCLASS="COMMAND">match</B>. For example, <TTCLASS="USERINPUT"><B>b=`expr $a : [0-9]*`</B></TT> is the exact equivalent of <TTCLASS="USERINPUT"><B>b=`expr match $a [0-9]*`</B></TT> in the above listing.</P><P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 3 echo 4 echo "String operations using \"expr \$string : \" construct" 5 echo "===================================================" 6 echo 7 8 a=1234zipper5FLIPPER43231 9 10 echo "The string being operated upon is \"`expr "$a" : '\(.*\)'`\"." 11 # Escaped parentheses grouping operator. == == 12 13 # *************************** 14 #+ Escaped parentheses 15 #+ match a substring 16 # *************************** 17 18 19 # If no escaped parentheses... 20 #+ then 'expr' converts the string operand to an integer. 21 22 echo "Length of \"$a\" is `expr "$a" : '.*'`." # Length of string 23 24 echo "Number of digits at the beginning of \"$a\" is `expr "$a" : '[0-9]*'`." 25 26 # ------------------------------------------------------------------------- # 27 28 echo 29 30 echo "The digits at the beginning of \"$a\" are `expr "$a" : '\([0-9]*\)'`." 31 # == == 32 echo "The first 7 characters of \"$a\" are `expr "$a" : '\(.......\)'`." 33 # ===== == == 34 # Again, escaped parentheses force a substring match. 35 # 36 echo "The last 7 characters of \"$a\" are `expr "$a" : '.*\(.......\)'`." 37 # ==== end of string operator ^^ 38 # (actually means skip over one or more of any characters until specified 39 #+ substring) 40 41 echo 42 43 exit 0</PRE></TD></TR></TABLE></P></TD></TR></TABLE></DIV></DD></DL></DIV><P>The above script illustrates how <BCLASS="COMMAND">expr</B> uses the <ICLASS="EMPHASIS">escaped parentheses -- \( ... \) --</I> grouping operator in tandem with <AHREF="regexp.html#REGEXREF">regular expression</A> parsing to match a substring. Here is a another example, this time from <SPANCLASS="QUOTE">"real life."</SPAN> <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 # Strip the whitespace from the beginning and end. 2 LRFDATE=`expr "$LRFDATE" : '[[:space:]]*\(.*\)[[:space:]]*$'` 3 4 # From Peter Knowles' "booklistgen.sh" script 5 #+ for converting files to Sony Librie format. 6 # (http://booklistgensh.peterknowles.com)</PRE></TD></TR></TABLE> </P><P><AHREF="wrapper.html#PERLREF">Perl</A>, <AHREF="sedawk.html#SEDREF">sed</A>, and <AHREF="awk.html#AWKREF">awk</A> have far superior string parsing facilities. A short <BCLASS="COMMAND">sed</B> or <BCLASS="COMMAND">awk</B> <SPANCLASS="QUOTE">"subroutine"</SPAN> within a script (see <AHREF="wrapper.html">Section 33.2</A>) is an attractive alternative to <BCLASS="COMMAND">expr</B>.</P><P>See <AHREF="string-manipulation.html">Section 9.2</A> for more on using <BCLASS="COMMAND">expr</B> in string operations.</P></DIV><H3CLASS="FOOTNOTES">Notes</H3><TABLEBORDER="0"CLASS="FOOTNOTES"WIDTH="100%"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="5%"><ANAME="FTN.AEN7354"HREF="moreadv.html#AEN7354">[1]</A></TD><TDALIGN="LEFT"VALIGN="TOP"WIDTH="95%"><P>And even when <ICLASS="FIRSTTERM">xargs</I> is not strictly necessary, it can speed up execution of a command involving batch processing of multiple files.</P></TD></TR></TABLE><DIVCLASS="NAVFOOTER"><HRALIGN="LEFT"WIDTH="100%"><TABLEWIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top"><AHREF="external.html">Prev</A></TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="index.html">Home</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top"><AHREF="timedate.html">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">External Filters, Programs and Commands</TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="external.html">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">Time / Date Commands</TD></TR></TABLE></DIV></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -