在Bash中使用尾随空格创建字符串 [英] Create string with trailing spaces in Bash

查看:69
本文介绍了在Bash中使用尾随空格创建字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是一个例子:

  declare -A my_arraymy_array ["k 1"] =值一"my_array [键二"] =值二"用于键入"$ {!my_array [@]}";做echo"$ key:$ {my_array [$ key]}"完毕 

输出为

  k 1:值一关键二:价值二 

我想要的输出是(对于任意键长):

  k 1:值一关键二:价值二 

解决方案

您可以使用 printf (如果您的系统具有):

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

这会将最大密钥长度硬编码为20,但是您当然可以添加遍历密钥的代码,计算最大密钥,然后使用该代码构建 printf 格式化字符串./p>

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

解决方案

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.

这篇关于在Bash中使用尾随空格创建字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆