In bash
on macOS
,我想写一个小脚本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
.
我该如何解决这些问题?
修改丹尼斯·威廉姆森的回答 https://stackoverflow.com/a/5043700/5291015稍微满足您的要求并将结果添加到数组中。适用于 GNUdate
而 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[@]}"
设置 GNUdate
在 MacOS 上你需要做brew install coreutils
并访问命令为gdate
以将其与提供的本机版本区分开来。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)