简体   繁体   English

用printf的空格扩展变量

[英]Expand a variable with spaces for printf

My script constructs variables into a given order depending on a table to be printed. 我的脚本根据要打印的表将变量构造为给定顺序。 But if there are any spaces in the end string, printf treats it as a separate column. 但是,如果结尾字符串中有空格,则printf会将其视为单独的列。 Imagine the following: 想象以下情况:

one=1
two="2 3"
all="$one $two"
format="%5s%5s"
printf $format $all

How can the printf command understand the variables passed in $all properly? printf命令如何正确理解$ all中传递的变量? I know they are being expanded and that printf is seeing it just as a single string, but I can't find a way to get it to work where there are spaces in a variable like there are in $four. 我知道它们正在扩展,并且printf只是将其视为单个字符串,但是我找不到在变量中有空格的地方(如$ four中)使它工作的方法。

It can't, as written. 按照书面规定,它不能。 You can't selectively treat some spaces as word splitting and others as not in a parameter expansion. 您不能选择性地将某些空格视为单词拆分,而另一些空格则不能视为参数扩展。 You can, however, use an array to preserve the non-word-splitting spaces. 但是,您可以使用数组保留非单词拆分空间。

one=1
two="2 3"
all=( "$one" "$two" )
format="%5s%5s"
printf "$format" "${all[@]}"

You should store the two values in an array rather than a string. 您应该将两个值存储在数组中而不是字符串中。

one=1
two="2 3"
all=("$one" "$two") # array with 2 elements
format="%5s%5s"
printf "$format" "${all[@]}" # quoting the array expansion properly passes two args

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

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