expr Command in Linux
Overview
The expr command in Linux is a powerful tool for performing arithmetic operations and handling strings directly in the command line. Its purpose lies in evaluating expressions, making it an essential command for scripting and complex computation tasks.
Syntax of expr Command in Linux
The basic syntax of the expr command in Linux is as follows:
Where:
- arg1: The first argument, which can be a number for arithmetic operations or a string for string operations.
- operator: This represents the operation to be performed. It can be arithmetic (like '+', '-', '*', '/') or string-related (':', '=', 'match', 'length').
- arg2: The second argument, like arg1, this can be a number or a string, depending on the operation.
Options in expr Command in Linux
-
Arithmetic Operations: expr can perform basic arithmetic operations.
For example -
Output:
This command adds the numbers 5 and 3.
-
String Length: expr can find the length of a string using the length operator.
For example -
Output:
This command calculates the length of the string 'Hello World'.
-
String Comparison: expr compares two strings lexicographically.
For example -
Output:
This command compares two strings. If they're equal, the output is 1; otherwise, it's 0.
Example Usages
-
Subtracting numbers:
Output:
Explanation: This command subtracts 3 from 5.
-
Matching a substring:
Output:
Explanation: This command matches the substring 'Hello' in 'Hello World'. The output is the length of the matching string.
Tips
-
Always space your arguments and operators when using the expr command in Linux, as it treats a lack of space as a single argument.
-
If a string contains special characters, use quotes to avoid bash interpreting them.
Advanced Use Cases of expr Command in Linux
-
Multiplying numbers:
Output:
Explanation: This command multiplies 5 and 3. Notice the backslash before the asterisk; it's needed because an asterisk without a backslash is a wildcard in bash.
-
Index of substring:
Output:
Explanation: This command finds the first position of the substring 'World' in 'Hello World'. The output starts from 1.
-
Substring extraction:
Output:
Explanation: This command extracts the substring starting from position 7 of length 5 from the string 'Hello World'.
Conclusion
-
The expr command in Linux is an essential tool for arithmetic and string operations.
-
Always remember to space out your arguments and operators in expr command.
-
The expr command in Linux also has string manipulation capabilities, such as finding the length, comparing strings, and extracting substrings.