【问题标题】:Count of number of Mondays in any month in Linux shell script [closed]Linux shell脚本中任何一个月的星期一数[关闭]
【发布时间】:2022-08-18 20:10:36
【问题描述】:

如何在 Linux shell 脚本中计算任何一个月的星期一数?

  • 你试过什么?它是如何失败的?
  • 除非您考虑这种作弊:使用cal 命令并以合适的方式解析输出。

标签: linux shell


【解决方案1】:

以下代码显示了如何
“Linux shell 脚本中任何一个月的星期一数”
可以实现:

# Choose the year in the following line
export year=2021
export month=1

while [ "$month" -lt 13 ]
do
   export day=1;
   export count=0;
   while [ "$day" -lt 32 ]
   do
      export anydate="$year""-""$month""-""$day"
      date "+%Y-%m-%d" -d "$anydate" > /dev/null  2>&1 
         if [ $? == 0 ] # check if date is valid
         then
             #--- following line is for debugging only
             #echo $anydate
             export weekday=`date -d $anydate +"%u"`
             if [ $weekday == 1 ]
             then
                export count=`expr $count + 1` 
             fi
         fi
         export day=`expr $day + 1`   
   done
   echo $year month $month Monday count $count
   export month=`expr $month + 1`
done

年度产出 = 2021:

2021 month 1 Monday count 4
2021 month 2 Monday count 4
2021 month 3 Monday count 5
2021 month 4 Monday count 4
2021 month 5 Monday count 5
2021 month 6 Monday count 4
2021 month 7 Monday count 4
2021 month 8 Monday count 5
2021 month 9 Monday count 4
2021 month 10 Monday count 4
2021 month 11 Monday count 5
2021 month 12 Monday count 4

一条关键线是

export weekday=`date -d $anydate +"%u"` 

它写了工作日的编号,其中 1 表示星期一。

如果任何其他行需要更多描述,请在评论中告诉我们。

【讨论】:

  • 请将答案标记为已接受,因为提供了您问题的解决方案:单击答案旁边的复选标记。谢谢。
  • 我不确定您的答案在技术上是否可以被接受,因为在您发布答案后问题已关闭。
  • 有趣的是,在我想按下发送按钮前几秒钟,问题就被关闭了。我要写一个评论。就在这时,问题又被打开了。我可以发布我的答案。但是之后就关门了……
猜你喜欢
  • 2016-07-06
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多