我可以使用 echo 和 bash 对齐字符串中的变量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2370839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:44:33  来源:igfitidea点击:

Can I align variables in a string with echo and bash?

bashshellechotabbing

提问by Kiran

I want to do formatting using echo in shell scripting.

我想在 shell 脚本中使用 echo 进行格式化。

Here is a small code snippet which is giving me the problem:

这是一个给我带来问题的小代码片段:

echo -en "\rFileName    :   $filename   :    $index of $lines Completed"

The $filenameis a string with varying length, and this is causing problem with formatting in the terminal. How can I overcome this?

$filename是一个长度可变的字符串,这会导致终端中的格式问题。我怎样才能克服这个问题?

Here's what I mean:

这就是我的意思:

FileName :       a800_102 :    6 of 6 Completed
FileName :       ersf_1024    :    56 of 56 Completed

I would like to have a table format when I display it on the terminal.

我想在终端上显示表格格式。

回答by richq

Use printf:

使用printf

printf "\rFileName : %20s : %8d of %8d Completed" $filename $index $lines