SHELL script strategy (Study Notes) -- 1.7 expr command full solution, -- 1.7 expr

Source: Internet
Author: User

SHELL script strategy (Study Notes) -- 1.7 expr command full solution, -- 1.7 expr

The expr command can be used to perform numeric operations, numeric or string comparison, string matching, string extraction, and string length calculation. It also has several special functions to determine whether a variable or parameter is an integer, empty, or 0.

First, let's look at the translation of the info document info coreutils 'expr invocation' of the expr command.

16.4.1 string expression ------------------------- 'expr' supports mode matching and string operations. The priority of a string expression is higher than that of a numeric expression and a logical relational expression. 'String: regex' execution mode matching. The two parameters are converted to the character format, and the second parameter is considered as a regular expression (GUN basic regular). By default, the prefix "^" is implicitly used ". Then match the first parameter with the regular expression. If the match is successful and the REGEX uses '\ (' and '\)', the expression returns the matched result. If the match fails, if '\ (' and '\)' is used in REGEX, this expression returns an empty string; otherwise, it returns 0. Only the first '\ (... \)' will reference the returned value. The other '\ (... \)' will only make sense when grouping regular expressions. In a regular expression, '\ + ','\? 'And' \ | 'sub-tables represent matching one or more, 0 or 1, and either of the two ends means. 'Match STRING regex' is equivalent to 'string: regex '. 'Substr string position length' returns the substring of the string starting from POSITION with the maximum LENGTH. If POSITION or LENGTH is negative, 0 or non-numeric, an empty string is returned. Any single character in 'index STRING charset' CHARSET is the top character in the STRING. If the character in CHARSET does not exist in STRING, 0 is returned. See the following example. 'Length string' returns the STRING length. '+ Token' parses the TOKEN into a normal string, even if the TOKEN is a keyword like MATCH or operator. This causes 'expr length + "$ x" 'or 'expr + "$ x ":'. */\(. \) ''can be tested normally, even if the value of" $ x "may be '/' or 'index. This operator is a GUN extension. For general portable versions, '"$ token":' \ (. * \) ''should be used instead of '+" $ token "'. To resolve the keyword to a common character, expr must be enclosed by quotation marks. 16.4.2 arithmetic expression ------------------------ 'expr' supports common arithmetic operations. The priority of an arithmetic expression is lower than that of a string expression and higher than that of a logical relational expression. '+-' Addition and subtraction. Parameters at both ends are converted to integers. If the conversion fails, an error is returned. '*/%' Multiplication, division, modulo operation. Parameters at both ends are converted to integers. If the conversion fails, an error is returned. 16.4.3 logical relationship expression --------------------------- 'expr' supports common logical connections and logical relationships. It has the lowest priority. '|' If the first parameter is not null and is not 0, the value of the first parameter is returned. Otherwise, the value of the second parameter is returned, however, the value of the second parameter is required to be non-null or non-0. Otherwise, 0 is returned. If the first parameter is not null or is not 0, the second parameter is not calculated. After testing, the content of the above manual is incorrect. If the first parameter is not 0, the value of the first parameter is returned. Otherwise, the second parameter is returned. If any parameter is null, an error is returned. Unless an empty string is enclosed by quotation marks, the processing method is the same as that of 0. '&' If both parameters are not null and not 0, the first parameter is returned; otherwise, 0 is returned. If the first parameter is 0 or null, the second parameter is not calculated. After testing, the content of the above manual is incorrect. If both parameters are not 0, the first parameter is returned. Otherwise, 0 is returned. If any parameter is null, an error is returned. Unless an empty string is enclosed by quotation marks, the processing method is the same as that of 0. '<<===! ==> 'Compare the parameters at both ends. If it is true, 1 is returned; otherwise, 0 is returned. "=" Is a synonym for "=. "Expr" first tries to convert the parameters at both ends into integers and perform arithmetic comparison. If the conversion fails, character comparison is performed based on character set sorting rules. Parentheses '()' can change the priority, but escape the parentheses with a backslash. 16.4.4 'expr' example --------------------------------- example of expr, in which shell metacharacters are surrounded by quotation marks. Increase the value of the variable 'foo' in shell by 1: foo = $ (expr $ foo + 1). The output variable PATH variable '$ fname' does not contain: expr $ fname :'. */\(. * \) ''| '$ fname explanation:' | 'is the connector in expr, but it is surrounded by quotation marks to prevent shell parsing. For example, $ fname =/etc/hosts, then this expression returns hosts. If $ fname =/usr/share/, the left side of this expression '|' is blank, therefore, the '|' value on the right is returned, that is, $ fname, that is,/usr/share /. An example showing that '\ +' is an operator: expr aaa: 'A \ + '# Explanation: \ (\) is not used in the REGEX part \(\), therefore, the number of matched characters => 3 expr abc: 'A \(. \) C' # Explanation: Because the REGEX part uses \ (\), the matched character => B expr index abcdef cz => 3 expr index a # explanation is returned: because the second index is the keyword error-> expr: syntax error expr index + index a # Explanation: Use + to resolve the index keyword to a common string => 0

The following example is used to introduce the usage of expr. Note the following three points before introduction:

(1 ).Numeric expressions ("+-*/%") and comparison expressions ("<===! ==>> ") Converts the parameters at both ends to numerical values. If the conversion fails, an error is returned. Therefore, you can use this to determine whether a parameter or variable is an integer.

(2) Many symbols in. expr must be escaped or enclosed by quotation marks.

(3). Both sides of all operators must have spaces.

The following is an example of expr.

(1). "string: REGEX" string matching example. To output the matched string results, you must use "\ (" and "\)". Otherwise, the number of matched strings is returned.

[root@xuexi ~]# expr abcde : 'ab\(.*\)'cde[root@xuexi ~]# expr abcde : 'ab\(.\)'c[root@xuexi ~]# expr abcde : 'ab.*'  5[root@xuexi ~]# expr abcde : 'ab.'   3[root@xuexi ~]# expr abcde : '.*cd*'4

Note that because the REGEX contains "^", the matching starts with the first character of the string.

[root@xuexi ~]# expr abcde : 'cd.*'  0

The true regular expression is "^ cd. *", while abcde starts with a rather than c, so no result can be matched. Therefore, any string matching should start with the first character.

When a string is matched, the parameters at both ends are converted to the character format.

(2) "index string chars" usage example.

This expression is used to search for the position of a character in chars from string. This character is the top character in string. For example:

[root@xuexi ~]# expr index abcde dec3

This command breaks down the string "dec" by character. First, the first character d is obtained, and the position of d is 4 from abcde, and then the second character e is obtained, the position of this character in abcde is 5, the final character is c, and the position of this character in abcde is 3. 3 is the top character, so the result returned by the command is 3.

[root@xuexi ~]# expr index abcde xdc3

If all characters in chars do not exist in string, 0 is returned.

[root@xuexi ~]# expr index abcde 10[root@xuexi ~]# expr index abcde 1x0

(3). "substr string pos len" usage example.

This expression is used to retrieve the substring from the string with the length of len starting from the pos position. If pos or len is not a positive integer, an empty string is returned.

[root@xuexi ~]# expr substr abcde 2 3bcd[root@xuexi ~]# expr substr abcde 2 4bcde[root@xuexi ~]# expr substr abcde 2 5bcde[root@xuexi ~]# expr substr abcde 2 0[root@xuexi ~]# expr substr abcde 2 -1

(4). "length string" usage example. This expression is the length of the returned string, where the string cannot be null. Otherwise, an error is returned, so it can be used to determine whether the variable is null.

[root@xuexi ~]# expr length abcde5[root@xuexi ~]# expr length 1113[root@xuexi ~]# expr length $xxxexpr: syntax error[root@xuexi ~]# if [ $? -ne 0 ];then echo '$xxx is null';fi$xxx is null

(5). "+ token" usage example.

Some symbols and keywords in expr have special meanings, such as "match", "index", and "length". To make it a character, use this expression to forcibly resolve any token to a normal string.

[root@xuexi ~]# expr index index dexpr: syntax error[root@xuexi ~]# expr index length gexpr: syntax error[root@xuexi ~]# expr index + length g4

In fact, you can use string matching to convert keywords into strings. For example:

[root@xuexi ~]# expr index 'length : "\(length\)"' g 4

For a variable whose value is a keyword, it doesn't matter.

[root@xuexi ~]# len=lenght[root@xuexi ~]# expr index $len g4

(6) Example of arithmetic operation usage.

[root@xuexi ~]# expr 1 + 23[root@xuexi ~]# a=3[root@xuexi ~]# b=4[root@xuexi ~]# expr $a + $b7[root@xuexi ~]# expr 4 + $a7[root@xuexi ~]# expr $a - $b-1

The arithmetic multiplication symbol "*" is a metacharacter in a regular expression. to escape it, You can enclose it with quotation marks or use a backslash.

[Root @ xuexi ~] # Expr $ a * $ bexpr: syntax error [root @ xuexi ~] # Expr $ a' * '$ b12 [root @ xuexi ~] # Expr $ a \ * $ b12 [root @ xuexi ~] # Expr $ B/$ a # Division can only take an integer of 1 [root @ xuexi ~] # Expr $ B % $ a1

Space is required at both ends of any operator; otherwise:

[root@xuexi ~]# expr 4+$a 4+3[root@xuexi ~]# expr 4 +$aexpr: syntax error

When performing arithmetic operations, expr first converts the parameters on both sides of the operator to integers. If the conversion fails at any end, an error is returned. Therefore, it can be used to determine whether a parameter or variable is an integer.

[root@xuexi ~]# expr $a + $cexpr: non-integer argument[root@xuexi ~]# if [ $? != 0 ];then echo '$a or $c is non-integer';fi          $a or $c is non-integer

(7). comparison operator <===! ==> Usage example. "<" And ">" are the positive anchored metacharacters of the regular expression, and "<" will be parsed as a redirection symbol by shell, so it must be escaped or surrounded by quotation marks.

These operators first convert the parameters at both ends to numerical values. If the conversion is successful, the values are compared. If the conversion fails, the character size is compared according to the character set sorting rules. If the comparison result is true, expr returns 1; otherwise, 0.

[root@xuexi ~]# a=3[root@xuexi ~]# expr $a = 10[root@xuexi ~]# expr $a = 31[root@xuexi ~]# expr $a \* 3 = 91[root@xuexi ~]# expr abc \> ab1[root@xuexi ~]# expr akc \> ackd1

(8). Example of logical connection symbols "&" and "|. Both symbols must be escaped or enclosed by quotation marks.

The following are the explanations provided in the official documentation, but they are not completely correct in actual use.

"&" Indicates that if both parameters are not empty and not 0, the value of the first parameter is returned. Otherwise, 0 is returned. If the first parameter is null or 0, skip the second parameter without any calculation.

"|" Indicates that if the first parameter is not empty and not 0, the first parameter value is returned; otherwise, the second parameter value is returned, but if the second parameter is null or 0, returns 0. If the first parameter is not null or is not 0, the second parameter is skipped without any calculation.

Which of the following statements is true:

"&" Indicates that if both parameters are not 0, the first parameter is returned; otherwise, 0 is returned. If any parameter is null, the expr error is returned. Unless an empty string is enclosed by quotation marks, the processing method is the same as 0.

"|" Indicates that if the first parameter is not 0, the value of the first parameter is returned. Otherwise, the second parameter is returned. If any parameter is null, an expr error is returned. Unless an empty string is enclosed by quotation marks, the processing method is the same as 0.

[root@xuexi ~]# expr $abc '|' 1expr: syntax error[root@xuexi ~]# expr "$abc" '|' 11[root@xuexi ~]# expr "$abc" '&' 1 0[root@xuexi ~]# expr $abc '&' 1 expr: syntax error[root@xuexi ~]# expr 0 '&' abc0[root@xuexi ~]# expr abc '&' 00[root@xuexi ~]# expr abc '|' 0abc[root@xuexi ~]# expr 0 '|' abc  abc[root@xuexi ~]# expr abc '&' cdeabc[root@xuexi ~]# expr abc '|' cdeabc

 

Back to series article outline: http://www.cnblogs.com/f-ck-need-u/p/7048359.html

Reprinted please indicate the source: http://www.cnblogs.com/f-ck-need-u/p/7231832.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.