本文介绍了在macOS上进行Bash-获取给定年份中每个星期六的日期列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

macOSbash中,我想用dates(或其他任何可以执行的程序)编写一个小脚本,该脚本以yyyymmdd的格式显示日期的每个星期六给定年份并将其保存到变量中.

In bash on macOS, I would like to write a small script with dates (or any other program that would do) that gives me a list of dates in the format yyyymmdd of every Saturday of a given year and saves it to a variable.

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

For example, if I wanted to have a list of dates for all Saturdays of the year 1850, it should somehow look like this:

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

但是,尽管上面的命令为我提供了正确的tee输出,但上面的命令并未在数组list中写入任何内容.

However, the above command does not write anything in the array list although it gives me the right output with tee.

如何解决这些问题?

推荐答案

修改 Dennis Williamson的答案略微满足您的要求并将结果添加到数组中.在GNU date上可用,而不在FreeBSD的版本上可用.

Modifying Dennis Williamson's answer slightly to suit your requirement and to add the results into the array. Works on the GNU date and not on FreeBSD's version.

#!/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

现在您可以将结果打印为

Now you can just print the results as

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


要在MacOS上设置GNU date,您需要执行brew install coreutils并以gdate身份访问该命令,以将其与提供的本机版本区分开.


To set up the GNU date on MacOS you need to do brew install coreutils and access the command as gdate to distinguish it from the native version provided.

这篇关于在macOS上进行Bash-获取给定年份中每个星期六的日期列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 17:26