简体   繁体   English

如何在 bash 的同一行打印多个空格然后打印 word?

[英]How to print many spaces and then print word on the same line in bash?

I need to print word with some spaces on the start of line, and I need to set spaces count with variable.我需要在行首打印带有一些空格的单词,并且需要使用变量设置空格计数。

This code is not working:此代码不起作用:

spaces=20

echo "spaces: $spaces"

for ((n=0;n<$spaces;n++))
do
    printf '%s' ''
done
    
printf '%s' 'hello!'

Real output:真正的 output:

spaces: 20

hello!

Expected output:预期 output:

spaces: 20
    
                    hello!

You can just use single printf to get desired number of padding of spaces:您可以只使用单个printf来获得所需的空格填充数:

printf '%*s\n' "$spaces" 'hello!'
               hello!

Change this:改变这个:

    printf '%s' ''

To this:对此:

    printf '%s' ' '

Or even this:甚至这样:

    printf ' '

Or just replace the whole program with:或者只是将整个程序替换为:

s=20; printf %$s's\n' "hello!"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM