在macOS上进行Bash - 获取给定年份每个星期六的日期列表

问题描述 投票:4回答:3

bashmacOS上,我想用dates(或任何其他可以做的程序)编写一个小脚本,它给出了一个给定年份每个星期六yyyymmdd格式的日期列表,并将其保存到变量中。

例如,如果我想要一个1850年所有星期六的日期列表,它应该看起来像这样:

var = [ 18500105, 18500112, 18500119, …, 18501228 ]

使用以下代码:

list=()
for month in `seq -w 1 12`; do
    for day in `seq -w 1 31`; do
    list=( $(gdate -d "1850$month$day" '+%A %Y%m%d' | grep 'Saturday' | egrep -o '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}' | tee /dev/tty) )
    done
done

但是,上面的命令不会在数组list中写入任何内容,尽管它使用tee为我提供了正确的输出。

我该如何解决这些问题?

bash macos date terminal
3个回答
2
投票

稍微修改Dennis Williamson's answer以满足您的要求并将结果添加到数组中。适用于GNU date,而不适用于FreeBSD的版本。

#!/usr/bin/env bash
y=1850

for d in {0..6}
do
    # Identify the first day of the year that is a Saturday and break out of
    # the loop
    if (( $(date -d "$y-1-1 + $d day" '+%u') == 6))
    then
        break
    fi
done

array=()
# Loop until the last day of the year, increment 7 days at a
# time and append the results to the array
for ((w = d; w <= $(date -d "$y-12-31" '+%j'); w += 7))
do
    array+=( $(date -d "$y-1-1 + $w day" '+%Y%m%d') )
done

现在您可以将结果打印为

printf '%s\n' "${array[@]}"

要在MacOS上设置GNU date,您需要执行brew install coreutils并以gdate身份访问命令,以区别于提供的本机版本。


2
投票

哎呀,刚才意识到你需要MacOS date

对于没有这种限制的其他人,我会留下答案,但这对你不起作用。

这不是你想要的,但是关闭:

year=1850
firstsat=$(date -d $year-01-01-$(date -d $year-01-01 +%w)days+6days +%Y%m%d)
parset a 'date -d '$firstsat'+{=$_*=7=}days +%Y%m%d' ::: {0..52}
echo ${a[@]}

它有错误,它发现了接下来的53个星期六,而最后一个可能不在当年。

parset是GNU Parallel的一部分。


1
投票

我没有做太多错误检查,但这是另一个实现。 将星期和目标年份作为参数。

获取所请求的第一个匹配工作日的朱利安日 - 获取当天中午的纪元秒 - 只要年份与请求的匹配,将该日期添加到数组并向跟踪变量添加一周的秒数。

泡沫,冲洗,重复,直到那一年不再。

$: typeset -f alldays
alldays () { local dow=$1 year=$2 julian=1;
  until [[ "$dow" == "$( date +%a -d $year-01-0$julian )" ]]; do (( julian++ )); done;
  es=$( date +%s -d "12pm $year-01-0$julian" );
  allhits=( $( while [[ $year == "$( date +%Y -d @$es )" ]]; do date +%Y%m%d -d @$es; (( es+=604800 )); done; ) )
}
$: time alldays Sat 1850
real    0m9.931s
user    0m1.025s
sys     0m6.695s

$: printf "%s\n" "${allhits[@]}"
18500105
18500112
18500119
18500126
18500202
18500209
18500216
18500223
18500302
18500309
18500316
18500323
18500330
18500406
18500413
18500420
18500427
18500504
18500511
18500518
18500525
18500601
18500608
18500615
18500622
18500629
18500706
18500713
18500720
18500727
18500803
18500810
18500817
18500824
18500831
18500907
18500914
18500921
18500928
18501005
18501012
18501019
18501026
18501102
18501109
18501116
18501123
18501130
18501207
18501214
18501221
18501228
© www.soinside.com 2019 - 2024. All rights reserved.