在bash中用等份分割数字

时间:2018-06-16 09:31:58

标签: linux bash shell unix

任何人都可以通过在bash脚本中将数字分成相等的部分来帮助我吗?

输入:

  • N = 1000
  • divide_by = 4

输出

  • 250,500,700,1000

2 个答案:

答案 0 :(得分:0)

使用算术表达式进行数学运算,并使用循环来打印序列。

#! /bin/bash
number=$1
divide_by=$2

(( part = number / divide_by ))
result=$part

while (( result <= number )) ; do
    printf '%d ' $result
    (( result += part ))
done
echo

请注意,对于具有非零余数的数字(例如1000和6),序列不会以初始数字结尾,而是以number - remainder结尾。

答案 1 :(得分:0)

你可以在bash中使用算法,例如incr=$((1000 / 4))然后您可以按for i in $(seq ${incr} ${incr} 1000)生成250,500,750,1000序列,例如