How to generate a range of nonweekend dates using tools available in bash?

左心房为你撑大大i 提交于 2020-01-24 17:52:05

问题


I want to generate a list of files where the name consists of ${filename}.${date}, for example file.20111101, file.20120703, starting November 1, 2011 until today and it should exclude weekends.

Thanks.


回答1:


try this for 2011

for y in 2011; do
  for m in {1..12}; do
    for d in  `cal -m $m $y|tail -n +3|cut -c 1-15`; do
      printf "file.%04d%02d%02d\n" $y $m $d;
    done;
  done;
done

or this for NOV-2011 to DEC-2013

for ym in {2011' '{11,12},{2012..2013}' '{1..12}}; do
  read y m <<<$ym;
  for d in  `cal -m $m $y|tail -n +3|cut -c 1-15`; do
    printf "file.%04d%02d%02d\n" $y $m $d;
  done;
done

or until end of this month "hard"

for ym in {2011' '{11,12},2012' '{1..7}};do
  read y m <<<$ym;
  for d in  `cal -m $m $y|tail -n +3|cut -c 1-15`;do
    printf "file.%04d%02d%02d\n" $y $m $d;
  done;
done



回答2:


This might work for you (GNU date,sed and Bash):

seq 0 $((($(date +%s)-$(date -d 20111101 +%s))/86400)) |
sed '5~7d;6~7d' |
xargs -l1 -I '{}' date -d '+{} days 20111101' +file.%Y%m%d

Explanation:

  • seq provides a sequence of days from 20111101 to today
  • sed filters out the weekends
  • xargs feeds day parameters for the date command.



回答3:


A solution with gawk:

gawk -v START_DATE="2011 11 01 0 0 0" -v FILE="file" '
  BEGIN {

    END_DATE   = strftime( "%Y %m %d 0 0 0", systime() )

    while ( START_DATE <= END_DATE ) {
      split( START_DATE, DATE )
      if ( strftime( "%u", mktime( START_DATE ) ) < 6 ) print FILE "." DATE[ 1 ] DATE[ 2 ] DATE[ 3 ]
      START_DATE = strftime( "%Y %m %d 0 0 0", mktime( DATE[ 1 ] " " DATE[ 2 ] " " ( DATE[ 3 ]+1 ) " 0 0 0" ) )
    }

  }
'

This uses a nice property of mktime that automatically find the correct date when you increment one of the date components (e.g. "2012-02-33" becomes "2012-03-04").




回答4:


Another option is to use dateseq from dateutils (http://www.fresse.org/dateutils/#dateseq).

$ dateseq 2017-03-25 $(date +%F) --skip sat,sun -ffile.%Y%m%d
file.20170327
file.20170328
file.20170329
file.20170330
file.20170331
file.20170403
file.20170404
file.20170405
file.20170406
file.20170407


来源:https://stackoverflow.com/questions/11314070/how-to-generate-a-range-of-nonweekend-dates-using-tools-available-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!