输出shell变量时如何保留空格? [英] How to preserve spaces when outputting a shell variable?
问题描述
出于字符串匹配的目的,我需要定义一个带前导空格的bash变量. 我需要从一个整数开始定义它,例如:
For string matching purposes I need to define a bash variable with leading spaces. I need to define this starting from an integer, like:
jj=5
printf在我看来是个好主意,因此,如果我想填充最多6个字符的空格:
printf seems to me a good idea, so if I want to fill spaces up to 6 character:
jpat=`printf " %6i" $jj`
但是当我尝试调出变量时却很不幸:
but unluckly when I am trying to recall the variable:
echo $jpat
前导空格被删除,我只得到$jj
整数.
the leading whitespaces are removed and I only get the $jj
integer as it was.
有任何解决方案来保留这样的空间吗?
Any solution to keep such spaces?
(这等效于:v=' val'; echo $v$v
.为什么输出中没有前导空格和多个空格?)
(This is equivalent to this: v=' val'; echo $v$v
. Why aren't there leading and multiple spaces in output?)
推荐答案
使用更多引号!
Use More Quotes! echo "$jpat"
will do what you want.
您正在执行的操作还有另一个问题:命令替换将删除尾随的换行符.在您使用的printf
命令中这不是问题,但是例如分配jpat=$(printf " %6i\n" "$jj")
将为您提供与命令完全相同的结果.
There is another issue with what you're doing: Command substitutions will remove trailing newlines. It's not an issue in the printf
command you're using, but for example assigning jpat=$(printf " %6i\n" "$jj")
would give you exactly the same result as your command.
这篇关于输出shell变量时如何保留空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!