添加到个位数变量为零 [英] Adding a zero to single digit variable
问题描述
尝试varaible前加一个零,如果是小于10,说创建目录。我似乎无法获得零到正确添加。不断产生使 2011年1月2日
, 2011年2月2日
等等,等等。
I = 0
因为我在{} 01..31
做
如果$ I> 10
然后
MKDIR $ PATH / 02.0 $ i.2011
其他
MKDIR $ PATH / 02 $ i.2011
科幻
DONE
您可以用替换一大堆:
因为我在0 {1..9} {} 10..31;做
MKDIR $ PATH / 02 $ i.2011
DONE
,同时仍然不具有启动任何外部过程(比可以是在循环体中其他)。
这可能不是那么重要的这里的,因为的mkdir
不是其中的一件事情你会做了很多在紧密循环,但它的将会的是重要的,如果你写了很多你的快速和肮脏的code的庆典
。
进程创建是昂贵的,当你做几十万次为我的一些脚本偶尔会做: - )
实例,所以你可以看到它在行动:
PAX $因为我在0 {7..9} {} 10..12;做回声$ I; DONE
07
08
09
10
11
12
和,如果你有最近的,足以庆典
的版本,它会兑现你的前几位要求:
一个序列的前pression的形式为
{x..y [..增量]}
,其中X
和是
要么是整数或单个字符,和增量
,一个可选的增量,是一个整数。当整数提供,前pression扩展到间X
是
,包容每个数字和。附送整数可能与0
pfixed $ P $迫使每个术语具有相同的宽度。当任X
或是
以0开头,外壳企图强迫所有生成的条款包含相同数量的数字,零填充在必要
块引用>因此,在我的Debian 6中,用
庆典
版本4.1.5:PAX $因为我在{07..11};做回声$ I; DONE
07
08
09
10
11Trying to add a zero before the varaible if it's less than 10 and create said directory. I can't seem to get the zero to add correctly. Keeps resulting in making
02.1.2011
,02.2.2011
etc,etc.i=0 for i in {01..31} do if $i > 10 then mkdir $path/02.0$i.2011 else mkdir $path/02.$i.2011 fi done
解决方案You can replace the whole lot with:
for i in 0{1..9} {10..31} ; do mkdir $path/02.$i.2011 done
while still not having to start up any external processes (other than what may be in the loop body).
That's probably not that important here since
mkdir
is not one of those things you tend to do a lot of in a tight loop but it will be important if you write a lot of your quick and dirty code inbash
.Process creation is expensive when you're doing it hundreds of thousands of times as some of my scripts have occasionally done :-)
Example so you can see it in action:
pax$ for i in 0{7..9} {10..12}; do echo $i; done 07 08 09 10 11 12
And, if you have a recent-enough version of
bash
, it will honor your request for leading digits:A sequence expression takes the form
{x..y[..incr]}
, wherex
andy
are either integers or single characters, andincr
, an optional increment, is an integer. When integers are supplied, the expression expands to each number betweenx
andy
, inclusive. Supplied integers may be prefixed with0
to force each term to have the same width. When eitherx
ory
begins with a zero, the shell attempts to force all generated terms to contain the same number of digits, zero-padding where necessary.So, on my Debian 6 box, with
bash
version 4.1.5:pax$ for i in {07..11} ; do echo $i ; done 07 08 09 10 11
这篇关于添加到个位数变量为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!