Groceries: Math Commands - bc/expr/dc/echo/awk

1. bc calculator

bc is an interactive calculator by default, and the following calculation symbols can be used:

  • + addition
  • - Subtraction
  • * Multiplication
  • /divide
  • ^ index
  • % remainder

interactive computation of bc

# bc
3+6 <=加法
9
4+2*3 <=加法、乘法
10
(4+2)*3 <=加法、乘法(优先)
18
4*6/8 <=乘法、除法
3
10^3 <=指数
1000
18%5 <=余数
3+4;5*2;5^2;18/4 <=一行输入多个计算,用;相隔。
7
10
25
4
scale=3 <=指定小数位
1/3
.333
quit

Non-interactive evaluation of bc: "echo ... | bc"

# echo "(6+3)*2" |bc
18
# echo 15/4 |bc
3
# echo "scale=2;15/4" |bc
3.75
# echo "3+4;5*2;5^2;18/4" |bc
7
10
25
4

non-decimal operation of bc

Use ibase (input) and obase (output) for operations.

  • Hexadecimal
  • Octal Octal
  • Binary
//将16进制的A7输出为10进制, 注意,英文只能大写
# echo "ibase=16;A7" |bc
167
//将2进制的11111111转成10进制
# echo "ibase=2;11111111" |bc
255
//输入为16进制,输出为2进制
# echo "ibase=16;obase=2;B5-A4" |bc
10001

bc takes the file name for calculation

# more calc.txt
3+2
4+5
8*2
10/4
# bc calc.txt
5
9
16
2

2. expr command

 expr computes addition, subtraction, multiplication and division and expressions.

One thing to note is to use spaces and escapes when calculating addition, subtraction, multiplication and division .

# expr 6 + 3 (有空格)
9
# expr 2 \* 3 (有转义符号\)
6
# expr 14 % 9
5
# a=3;expr $a+5 (无空格)
3+5
# expr $a + 5 (变量,有空格)
8
# a=`expr 4 + 2`;echo $a
6
# expr $a + 3
9

 Calculation of expr on strings

//字串长度
# expr length "yangzhigang.cublog.cn"
21

//从位置处抓取字串
# expr substr "yangzhigang.cublog.cn" 1 11
yangzhigang

//字串开始处
# expr index "yangzhigang.cublog.cn" cu
13

3. dc command

Not many people use dc for calculations, because dc is more complicated than bc, but when it comes to simple planning, it is similar and not difficult. dc is a stack operation, which is also interactive by default, but it can also be matched with echo and |.
Such as:

# dc
3
2+
p
5
4*
p
20
quit
# echo 3 2+ 4* p |dc
20

4. echo simple calculation

It is well known that echo is used for echoing. The above is also calculated with bc.

echo does simple calculations alone

Such as:

# echo $((3+5))
8
# echo $(((3+5)*2))
16

echo calculates variables

Such as:

# a=10;b=5;echo $(($a+$b))
15
# echo $a+$b
10+5
# echo $a+$b |bc
15

//计算前天的日期
# echo `date +%Y%m%d`
20090813
# echo `date +%Y%m%d`-2
20090813-2
# echo `date +%Y%m%d`-2 |bc
20090811

5. awk

When awk processes files, it can perform calculations, and of course it can also be used for calculations alone.
Such as:

# awk 'BEGIN{a=3+2;print a}'
5
# awk 'BEGIN{a=(3+2)*2;print a}'
10 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325927810&siteId=291194637