expr - Unix, Linux Command


Advertisements


NAME

expr - Evaluate an expression

SYNOPSIS

expr EXPRESSION
expr OPTION

DESCRIPTION

expr is a command line Unix utility which evaluates an expression and outputs the corresponding value. expr evaluates integer or string expressions, including pattern matching regular expressions. Most of the challenge posed in writing expressions is preventing the invoking command line shell from acting on characters intended for expr to process. The operators available for integers: addition, subtraction, multiplication, division and modulus for strings: find regular expression, find a set of characters in a string; in some versions: find substring, length of string for either: comparison (equal, not equal, less than, etc.)

Options

Tag Description
--help Display a help message and exit.
--version Display version information and exit.

EXAMPLES

Example-1:

To perform addition of two numbers:

$ expr 3 + 5

output:

8

Example-2:

To  perform substraction of two numbers:

$ expr 5 - 3

output:

2

Example-3:

To perform multiplication of two numbers ( note: The multiplication operator (*) must be escaped when used in an arithmetic expression with expr )

$ expr 5 \* 3

output:

15

Example-4:

To perform division operation:

$ expr 10 / 2

output:

5

Example-5:

To increament variable :

$ y=10

$ y=`expr $y + 1`

$ echo $y

output:
11

Example-6:

To find length of string

a=hello

b=`expr length $a`

echo $b

output:

5

Example-7:

To find the index/position of character in a string

a=hello

b=`expr index $a l`

echo $b

output:

3 (  as letter l is at position 3.)

Example-8:

To find substring of string:

a=hello

b=`expr substr $a 2 3` ( where 2 is position and 3 is length, command is to get substring from position 2 of length 3 characters)

echo $b

output:

ell

Example-9:

The following is an example involving boolean expressions ( |-  or operator ):

$ expr length  "abcdef"  "<"  5  "|"  15  -  4  ">"  8

output:
1

Example-10:

The following is an example involving boolean expressions ( & - and operator ):

$ expr length  "abcdef"  "<"  5  "&"  15  -  4  ">"  8

output:
0


Advertisements