【问题标题】:Printing array elements without white space using printf使用 printf 打印没有空格的数组元素
【发布时间】:2014-05-07 21:23:08
【问题描述】:

我可以在循环中使用 echo 打印我的数组元素,但输出格式非常糟糕。在那里我尝试注入制表符,但元素之间只有很多空格,因为每个元素的长度都不同。我不知道如何使用 printf ?我试过了,但它只是不能正常工作。有没有办法格式化我的 printf 或 echo 以便每个元素之间有相等数量的空格?这让我发疯。

while [[ $counter -lt $nai ]];
do
#echo ${slist[$counter]} $'\t' ${sstate[$counter]} $'\t' $'\t' ${scached[$counter]}
printf ${slist[$counter]} $'\t' ${sstate[$counter]} $'\t' $'\t' ${scached[$counter]}
counter=$(( $counter + 1 ))
done

简而言之,我只想以这样的元素之间具有相同数量空格的格式打印我的元素

  abc  cdf  efg

我得到的是

  abc       cdf            efg

谢谢

【问题讨论】:

标签: arrays bash printf echo


【解决方案1】:

如果要打印元素之间有N个空格,可以使用printf:

a="foo"
b="somestring"
c="bar"

# Print each argument with three spaces between them
printf "%s   " "$a" "$b" "$c"
# Print a line feed afterwards
printf "\n"

这会导致:

foo   somestring   bar
otherdata   foo   bar

您还可以使用%-12s 格式将每个元素填充为 12 个字符:

# Pad each field to 12 characters
printf "%-12s" "$a" "$b" "$c"
printf "\n"

导致:

foo         somestring  bar         
otherdata   foo         bar

【讨论】:

    【解决方案2】:

    尝试使用带有 printf 的格式字符串

    printf "%s  %s  %s\n" ${slist[$counter]} ${sstate[$counter]} ${scached[$counter]}
    

    如果字段没有空格,请使用column -t

    {
    echo my dog has fleas
    echo some random words here
    } | column -t
    
    my    dog     has    fleas
    some  random  words  here
    

    或者,在你的情况下:while ...; do ...; done | column -t

    【讨论】:

    • 感谢它好多了.. 间距相等.. 但由于元素的长度不相等,它们仍然没有正确对齐。有没有办法正确对齐它们?
    • 答案已更新。显示不止一行的示例输入会很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 2014-10-25
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2021-01-24
    相关资源
    最近更新 更多