1. bc
An arbitrary precision calculator language
scale: decimal arithmetic
ibase/obase: decimal/binary/octal/hexadecimal
math library: bc -l, –mathlib
s(x) # sine
c(x) # cosine
a(x) # arctangent
l(x) # logarithm
e(x) # exponential
j(n,x) # bessel of integer order n of x
echo "(6/4+2^5)*3" | bc
echo "scale=2;4/3" | bc
echo "ibase=16;A8" | bc
echo "ibase=2;obase=8;1111" | bc
variable=$(echo "OPTIONS; OPERATIONS" | bc)
interest_rate=$(echo "scale=9; $interest/12 + 1.0" | bc)
num_ibase=`echo "ibase=$ibase; $number" | bc`
variable=$(bc << EOF
options
statements
operations
EOF
)
[root@localhost ~]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
1+2
3
5/7
0
# Pi
[root@localhost ~]# echo "scale=10; a(1)*4" | bc -l
3.1415926532
[root@localhost ~]# echo "ibase=16; 0A" | bc
10
[root@localhost ~]# echo "ibase=16; obase=8; 0A" | bc
12
[root@localhost ~]# echo "ibase=16; obase=2; 0A" | bc
1010
2. dc, 压栈操作
**a reverse-polish desk calculator))
echo "2 3 + 4 * p" | bc
3. expr
evaluate expressions
expr ARG1 operator ARG2
expr STRING : REGEXP
expr match STRING REGEXP
expr substr STRING POS LENGTH
expr index STRING CHARS
expr length STRING
expr 3 + 5
expr 2 \* 5
expr length "abc123"
expe substr "abc123" 4 3
expr index "abc123" "1"
[root@localhost ~]# expr 10 % 3
1
# anchored pattern match of REGEXP in STRING
[root@localhost ~]# expr 'baidu.com' : '[a-z]'
1
[root@localhost ~]# expr 'baidu.com' : '[0-9]'
0
[root@localhost ~]# expr match 'baidu.com' '[a-z]'
1
# sub string, start with 1, not 0
[root@localhost ~]# expr substr 'google.com' 0 6
[root@localhost ~]# expr substr 'google.com' 1 6
google
# index
[root@localhost ~]# expr index 'google.com' '\.'
7
# length
[root@localhost ~]# expr length 'google.com'
10
4. sub-shell
echo $((3*2))
5. awk
awk 'BEGIN{a=1+2; print a}'
6. factor, 分解质因数
[root@localhost ~]# factor 1286262
1286262: 2 3 3 19 3761
# whether is a prime number
check_prime()
{
local factors=( $(factor $1) )
if [ -z "${factors[2]" ]; then
echo "$1 is a prime number."
fi
}