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


#1

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…?


#2

Hi,

try something like:

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

lubos


#3

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:


#4

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

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


#6

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

#7

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.


#8

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


#9

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-


#10

#11