Search code examples
bashzsh

ncal command question find number of Mondays


how can I find the number of Mondays that falls on the first of each month in a given year with the cal command. I've tried so far grepping each line that contains Mo

ncal 2021 | grep Mo

Solution

  • It is simple in the ncal format. Here is the output of ncal 2012:

                                  2012
        January           February          March             April
    Su  1  8 15 22 29        5 12 19 26        4 11 18 25     1  8 15 22 29
    Mo  2  9 16 23 30        6 13 20 27        5 12 19 26     2  9 16 23 30
    Tu  3 10 17 24 31        7 14 21 28        6 13 20 27     3 10 17 24
    We  4 11 18 25        1  8 15 22 29        7 14 21 28     4 11 18 25
    Th  5 12 19 26        2  9 16 23        1  8 15 22 29     5 12 19 26
    Fr  6 13 20 27        3 10 17 24        2  9 16 23 30     6 13 20 27
    Sa  7 14 21 28        4 11 18 25        3 10 17 24 31     7 14 21 28
    
        May               June              July              August
    Su     6 13 20 27        3 10 17 24     1  8 15 22 29        5 12 19 26
    Mo     7 14 21 28        4 11 18 25     2  9 16 23 30        6 13 20 27
    Tu  1  8 15 22 29        5 12 19 26     3 10 17 24 31        7 14 21 28
    ...
    

    How would you solve the task by hand?

    • Look only at the lines starting with Mo
    • In those lines, search for 1.
    • Write down the total number of found 1s.

    These three steps correspond to the following three commands after ncal:

    #! /usr/bin/env bash
    year=$1
    ncal "$year" | grep '^Mo' | grep -wo 1 | wc -l