简体   繁体   中英

How to print range in unix based on the 1st column

I want my output in two columns. The 1st column is the output of a date function which is incremental. I have used the below loop which will give me the output of date function.

start=20200926 
end=$(date -d"2 days ago" +"%Y%m%d")

while [[ $start -le $end ]]
do
        echo $start
        start=$(date -d"$start + 1 day" +"%Y%m%d")
done
20200930
20201001
20201002
20201003
20201004
20201005
20201006
20201007
20201008
20201009
20201010
20201011

So, when the date column increases i want my 2nd column value also to change accordingly. Suggest me a script

Output:

20200926  2140
20200927  2140
20200928  2140
20200929  2140
20200930  2140
20201001  2140
20201002  2140
20201003  2141
20201004  2141
20201005  2141
20201006  2141
20201007  2141
20201008  2141
20201009  2141
20201010  2142
20201011  2142

One idea for incrementing a counter after every X times through a loop:

col2=2140                                           # starting value for column #2
x=0                                                 # incremental counter; +1 on each pass through loop
y=3                                                 # number of times through loop before incrementing ${col2}

while [[ "${col2}" -le 2142 ]]                      # for demo purposes we'll loop until col2=2142
do
    echo "${col2}"
    x=$((x+1))
    [[ $(( $x % $y )) -eq 0 ]] && col2=$((col2+1))  # when x=y=7 (7 modulo 7 = 0) increment col2
done

This generates:

2140
2140
2140
2141
2141
2141
2142
2142
2142

Adding to OPs code and using y=7 :

start=20200926
end=$(date -d"2 days ago" +"%Y%m%d")
col2=2140
x=0
y=7

while [[ $start -le $end ]]
do
        echo "${start} ${col2}"
        start=$(date -d"${start} + 1 day" +"%Y%m%d")
        x=$((x+1))
        [[ $(( ${x} % ${y} )) -eq 0 ]] && col2=$((col2+1))
done

This generates:

20200926 2140
20200927 2140
20200928 2140
20200929 2140
20200930 2140
20201001 2140
20201002 2140
20201003 2141
20201004 2141
20201005 2141
20201006 2141
20201007 2141
20201008 2141
20201009 2141
20201010 2142
20201011 2142

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM