在 Bash 中创建尾随空格的字符串

发布于 2024-12-26 23:46:05 字数 423 浏览 4 评论 0原文

我想循环关联数组并以一种很好的方式打印出键/值对。因此,我想以这样的方式缩进这些值,使它们都从各自键后面的相同位置开始。

这是一个例子:

declare -A my_array
my_array["k 1"]="value one"
my_array["key two"]="value two"
for key in "${!my_array[@]}"; do
  echo "$key: ${my_array[$key]}"
done

输出是

k 1: value one
key two: value two

我想要的输出是(对于任意密钥长度):

k 1:     value one
key two: value two

I'd like to loop over an associative array and print out the key / value pairs in a nice way. Therefore I'd like to indent the values in such a way, that they all start at the same position behind their respective keys.

Here's an example:

declare -A my_array
my_array["k 1"]="value one"
my_array["key two"]="value two"
for key in "${!my_array[@]}"; do
  echo "$key: ${my_array[$key]}"
done

The output is

k 1: value one
key two: value two

The output I'd like to have would be (for arbitrary key length):

k 1:     value one
key two: value two

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

待天淡蓝洁白时 2025-01-02 23:46:05

您可以使用 printf,如果您的系统有的话

printf "%20s: %s" "$key" "${my_array[$key]}"

:将最大密钥长度硬编码为 20,但您当然可以添加代码来迭代密钥、计算最大值,然后使用它来构建 printf 格式化字符串。

You can use printf, if your system has it:

printf "%20s: %s" "$key" "${my_array[$key]}"

This hard-codes the maximum key length to 20, but you can of course add code that iterates over the keys, computes the maximum, and then uses that to build the printf formatting string.

听风吹 2025-01-02 23:46:05

使用 printf 而不是 echo。您将获得格式化的所有功能,例如 30 个字符的字段的 %30s

Use printf instead of echo. You'll get all the power of formatting, e.g. %30s for a field of 30 characters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文