Bash 中的空格连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7693736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Whitespace concatenation in Bash
提问by ciembor
The problem is simple.
问题很简单。
for i in `seq $begin $progress_length` ; do
progress_bar=$progress_bar'#'
done
for i in `seq $middle $end` ; do
empty_space=$empty_space' '
done
I need empty_spaceto position content after the progress bar. I've expected that it will be string of x whitespaces. But finally string is empty. How may I create string of x whitespaces?
我需要empty_space在进度条之后定位内容。我预计它将是一串 x 空格。但最后字符串是空的。如何创建 x 空格字符串?
回答by Diego Sevilla
The problem may be because $empty_spacehas only spaces. Then, to output them you have to surround it in double quotes:
问题可能是因为$empty_space只有空格。然后,要输出它们,您必须用双引号将其括起来:
echo "${empty_space}some_other_thing"
You can try more interesting output with printffor example to obtain several spaces. For instance, to write 20 spaces:
您可以尝试更有趣的输出,printf例如获得多个空格。例如,要写 20 个空格:
v=`printf '%20s' ' '`
回答by Fritz G. Mehner
The strings can be created using parameter substitution. The substitution ${str:offset:length} returns a substring of str :
可以使用参数替换来创建字符串。替换 ${str:offset:length} 返回 str 的子字符串:
space80=' '
hash80='################################################################################'
progress_bar=${hash80:0:$progress_length-$begin+1}
empty_space=${space80:0:$end-$middle+1}
echo -n "$empty_space$progress_bar"
回答by ekqnp
I understand your problem as I had exactly the same.
我理解你的问题,因为我遇到了完全相同的问题。
My solution was to concatenate a temporary character instead of a whitespace, say for example ?, and then, at the end, replace all their occurences with sedby a whitespace :
我的解决方案是连接一个临时字符而不是空格,例如?,然后,最后,用sed空格替换它们的所有出现:
echo $myString | sed 's/?/ /g'
I hope it will help you !
我希望它会帮助你!

