如何使用bash大括号扩展来制作乘法表?到目前为止,我有这个:echo $ [{1..10} * {1..10}] [英] How can I make a multiplication table using bash brace expansion? So far I have this: echo $[{1..10}*{1..10}]

查看:59
本文介绍了如何使用bash大括号扩展来制作乘法表?到目前为止,我有这个:echo $ [{1..10} * {1..10}]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更深入地学习bash,因此我决定制作一个乘法表.我具有以下语句的功能:

I am trying to learn bash at a deeper level, and I decided to make a multiplication table. I have the functionality with the statement :

echo $[{1..10}*{1..10}]

但这给了我以下输出:

1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100

有没有办法仅使用1条语句来格式化此输出,如下所示(我可以弄清楚如何使用循环来完成此操作,但这很有趣:p)

Is there any way to format this output like the following using only 1 statement (i can figure out how to do this with loops, but that's no fun :p )

1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 
6 12 18 24 30 36 42 48 54 60 
7 14 21 28 35 42 49 56 63 70 
8 16 24 32 40 48 56 64 72 80 
9 18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100

是否有可能在一条语句中执行此操作,或者我是否必须循环?

Is it even possible to do in one statement, or would I have to loop?

推荐答案

在不使用循环的情况下,使用此行可得到良好的输出:

Use this line for a nice output without using loops:

echo $ [{1..10} * {1..10}] |xargs -n10 |列-t

输出:

1   2   3   4   5   6   7   8   9   10
2   4   6   8   10  12  14  16  18  20
3   6   9   12  15  18  21  24  27  30
4   8   12  16  20  24  28  32  36  40
5   10  15  20  25  30  35  40  45  50
6   12  18  24  30  36  42  48  54  60
7   14  21  28  35  42  49  56  63  70
8   16  24  32  40  48  56  64  72  80
9   18  27  36  45  54  63  72  81  90
10  20  30  40  50  60  70  80  90  100


更新

作为合理的下一步,我在此处此乘法表的范围是否可变.使用此帮助,我的答案适用于变量( $ boundary )范围,并保持可读性:

As a logical next step, I asked here if this multiplication table can have a variable range. With this help, my answer works with a variable ($boundary) range and stays quite readable:

boundary = 4;评估回声$ \ [{1 .. $ boundary} * {1 .. $ boundary} \] |xargs -n $ boundary |列-t

输出:

1  2  3   4
2  4  6   8
3  6  9   12
4  8  12  16

还请注意,不赞成使用 $ [..] 算术符号,而应改用 $((...)):

Also note that the $[..] arithmetic notation is deprecated and $((...)) should be used instead:

boundary = 4;eval eval echo"$ \(\({1 .. $ boundary} * {1 .. $ boundary} \)\)" |xargs -n $ boundary |列-t

这篇关于如何使用bash大括号扩展来制作乘法表?到目前为止,我有这个:echo $ [{1..10} * {1..10}]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆