如何简化我的 bash 代码?
我在 bash 中编写了以下代码,该代码倾向于打印 200x13 随机数的矩阵(我们有 200 行,每行打印 13 个数字)。我希望这段代码更加灵活,以便可以更改打印矩阵的大小(行数和每行数),而无需重新编写代码,
for (( k = 0; k < 200; k++ ))
do
echo $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 ))
done
感谢任何帮助。
I've write the following code in bash, this code tends to print a matrix of 200x13 random numbers (we have 200 line printed with 13 numbers per line). I want this code to be more flexible such that one can change size of the matrix printed (number of line and number of number per line) without re-write the code
for (( k = 0; k < 200; k++ ))
do
echo $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 ))
done
thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您想要将列的打印更改为另一个 for 循环:
然后,您可以参数化您的 k max 和 j max:
First, you want to change the printing of the columns to another for-loop:
Then, you can parametrize your k max and j max:
将其放入 shell 函数 并使用 printf 而不是
echo
。由于这是在 shell 函数中,因此您可以获取函数定义并直接从 shell 调用它。如果该函数位于名为 shfuncs 的文件中,那么您可以获取它并按如下方式运行它:
Put it in a shell function and use printf instead of
echo
.Since this is in a shell function, you can source the function definition and call it directly from the shell. If the function is in a file named shfuncs, then you can source it and run it like follows:
要简单地做到这一点,只需添加一个嵌套循环来重复列即可。
另外,在 bash 中,您可以使用大括号扩展执行 for 循环...
如果脚本将变得更加复杂。我建议将脚本抽象为函数。
然后用这种方式调用它,
您可以更轻松地维护脚本并适应更改,例如,如果您需要使用
printf
格式化输出,如 D.Shawley 的答案所示。当然,您可能需要各种可能的视觉格式(左/右列对齐等),这些可以通过各种技巧来实现... 有关 shell 文本格式的更多信息To do this simply, just add a nested loop to repeat the columns.
Also in bash you can do a for loop with brace expansion ...
If the script was going to become more complicated. I'd suggest abstracting the script into functions.
Then call it with
This way you can more easily maintain the script and adapt to changes, e.g. if you needed to format the output using
printf
as shown in D.Shawley's answer. Of course you may want a variety of possible visual formatting (left/right column alignment etc.) these can be achieved with a variety of tricks... More on shell text formatting