【问题标题】:Bash Nested Loops, mixture of dates and numbersBash 嵌套循环,日期和数字的混合
【发布时间】:2010-10-07 18:31:25
【问题描述】:

我正在尝试输出一系列具有不同日期和相关数字的命令。每小时例如。

我试图在循环中做的输出是:

shell.sh filename<number e.g. between 1-24> <date e.g. 20100928> <number e.g. between 1-24> <id>

因此,基本上上述内容将为每个特定日期生成 24 次输出,并具有唯一的 4 位 id。

我想有一个嵌套循环,因为批号需要​​是唯一的。

谁能帮忙?

【问题讨论】:

    标签: bash for-loop nested-loops


    【解决方案1】:

    尚不清楚为什么需要嵌套循环,或者是否需要迭代一系列日期。但是脚本看起来像这样:

    #!/bin/bash
    
    DAY_FROM=1 # This is a first (starting) day
    DAY_TO=24  # This is the last day
    
    DATE=$(date +%Y%m%d) # This is a date we are processing.
    
    id=0 # This is a number for our unique ID generation.
         # It is being incremented for each day.
         # Since this variable is in global scope,
         # it will be unique no matter how many dates you process.
         # If you want unique ID be unique only for date scope,
         # reset it to 0 before processing each date.
    
    # Let's go iterate over all days.
    for (( i=$DAY_FROM; i <= $DAY_TO; ++i ))
    do
        let ++id # Increment our unique ID number...
        # Print filename, date, number and unique ID.
        # %04d at the end means that we output an integer
        # with 4 digits padded with zeroes if needed.
        printf "%s %s %s %04d\n" "filename$i" "$DATE" "$i" "$id"
    done
    

    ...输出会是这样的:

    filename1 20101007 1 0001
    filename2 20101007 2 0002
    filename3 20101007 3 0003
    ....
    

    希望对你有帮助!

    【讨论】:

    • 嘿弗拉德,谢谢。我想做一个嵌套循环,因为我需要的输出如下: filename1 20101007 01 0001 filename2 20101007 02 0002 filename3 20101007 03 0003 filename4 20101007 04 0004 filename5 20101007 05 0005 filename6 2010100............. ..... .. .... to filename24 20101007 24 0024 filename25 20101008 01 0025 (你可以看到一个新的集合开始于不同的日期,这个过程继续进行 n 日期迭代)这就是为什么我在想嵌套循环:-S
    【解决方案2】:

    我想做一个嵌套循环,因为我需要的输出如下:

    filename1 20101007 01 0001
    filename2 20101007 02 0002
    filename3 20101007 03 0003
    filename4 20101007 04 0004
    filename5 20101007 05 0005
    filename6 20101007 06 0006
    ......... ........ .. ....
    to
    filename24 20101007 24 0024
    
    filename25 20101008 01 0025
    

    (你可以看到一个新的集合开始于不同的日期,这个过程会持续 n 次迭代)

    这就是我想嵌套循环的原因:-S

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多