![bash 中的 printf 命令](https://linux22.com/image/137284/bash%20%E4%B8%AD%E7%9A%84%20printf%20%E5%91%BD%E4%BB%A4.png)
printf "%50s\n" " I ate 4 eggs"
在此示例中,我想从变量中分配 50。如何在 bash 的 for 循环中使用该变量?
任何想法?
答案1
至少对于bash
,您可以使用 C 样式printf
*
转换修饰符传递可变字段宽度:
width=50
printf '%*s\n' $width "I ate 4 eggs"
I ate 4 eggs
man 3 printf
详情请参阅。
如何在 for 循环中使用它取决于您想要的输出是什么。
根据您的评论,您可以使用
for i in {45..50}; do
for j in {1..13}; do
printf '%*.*s\n' $i $j "I ate 4 eggs"
done
done
提供字段宽度和精度作为变量,导致
I
I
I a
I at
I ate
I ate
I ate 4
I ate 4
I ate 4 e
I ate 4 eg
I ate 4 egg
I ate 4 eggs
I ate 4 eggs
I
I
I a
I at
I ate
I ate
I ate 4
I ate 4
I ate 4 e
I ate 4 eg
I ate 4 egg
I ate 4 eggs
I ate 4 eggs
等等。
答案2
您可以将 50 分配给变量,如下所示:
variable=50
您可以在 for 循环中使用该变量,如下所示:
for i in foo bar baz; do
printf "%${variable}s\n" "I ate 4 eggs"
done
如果您尝试增加 printf 语句上的填充,您可以执行以下操作:
$ for i in {45..50}; do printf "%${i}s\n" "I ate 4 eggs"; done
I ate 4 eggs
I ate 4 eggs
I ate 4 eggs
I ate 4 eggs
I ate 4 eggs
I ate 4 eggs