Counting number of weekends in a month (given or not) with BASH

Hello there!

I’m trying to count how many weekends there are in a given month, but I can’t figure it out how to count them correctly… I thought ncal + grep commands would do the job, but they don’t work or I use AND with grep incorrectly.

My try was:

ncal 10 2015 | grep 'Sa.*Su' | echo "Weekends count: "$((`wc -w`))

But this one doesnt work. Should I use date or something…?

Hi,

try something like:

$ ncal 10 2015 | grep -E 'Su|Sa' | echo "Weekends count: "$(( `wc -w` - 2))
Weekends count: 9

lubos

Hi,

try something like:

$ ncal 10 2015 | grep -E 'Su|Sa' | echo "Weekends count: "$(( `wc -w` - 2))
Weekends count: 9

lubos

But there are only 5 Saturdays and 4 Sundays n october of 2015, so it should be 4 weekends… :confused:

Right…what about this:

Example:


December:
$ echo -n "Weekends count: "; ncal 12 2015 | grep -E 'Su|Sa' | echo $(( `wc -w` - 2))/2 | bc
Weekends count: 4
May:
$ echo -n "Weekends count: "; ncal 5 2015 | grep -E 'Su|Sa' | echo $(( `wc -w` - 2))/2 | bc
Weekends count: 5

This is better, but it’s division, so not as good as it could be.

grep -E 'Su|Sa'

I understand this part as an ‘OR’. Is there any way to grep and count lines with AND? :confused: Thanks by the way!

Hi,

I’m quite unclear on how we can achieve this with counting lines and AND please explain further. We are currently counting words per line where Su and Sa shows only once. eg:

$ ncal 5 2015
    May 2015          
Su     3 10 17 24 31
Mo     4 11 18 25   
Tu     5 12 19 26   
We     6 13 20 27   
Th     7 14 21 28   
Fr  1  8 15 22 29   
Sa  2  9 16 23 30

Hi,

I’m quite unclear on how we can achieve this with counting lines and AND please explain further. We are currently counting words per line where Su and Sa shows only once. eg:

$ ncal 5 2015
    May 2015          
Su     3 10 17 24 31
Mo     4 11 18 25   
Tu     5 12 19 26   
We     6 13 20 27   
Th     7 14 21 28   
Fr  1  8 15 22 29   
Sa  2  9 16 23 30

Oh, that’s right… it’s quite unlogical. I figured that the good way out would be to check if the first day of month is Sunday and the last day is Saturday. If any of these two condition are met, then one weekend must be substracted. For example, february of 2015 starts on Sunday and ends on Saturday, so both conditions are met =>> 5-2=3 weekends. Am I right? I was looking at calendar and figured this out. Anyway, I don’t know how to write it.

(days/7)*2 + number of sat/sun in the last (days%7) days.

I understand for archive This is better, but it’s division, so not as good as it could be. for Counting number of weekends in a month-