添加到个位数变量为零 [英] Adding a zero to single digit variable

查看:122
本文介绍了添加到个位数变量为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试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
11

Trying 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 in bash.

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]}, where x and y are either integers or single characters, and incr, an optional increment, is an integer. When integers are supplied, the expression expands to each number between x and y, inclusive. Supplied integers may be prefixed with 0 to force each term to have the same width. When either x or y 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆