On the Linux CLI, is there a way to get the number of the week of the month? Maybe there is another way to get this with one simple (like date) command? Let's say that day 1 to 7 is the first week, day 8 to 14 is the second week, and so on.
Asked
Active
Viewed 2.1k times
5 Answers
2
You can use this:
Monday First week day
WEEKNUMBER=$(( 1 + $(date +%V) - $(date -d "$(date -d "-$(($(date +%d)-1)) days")" +%V) ))
Sunday Firs week daty
WEEKNUMBER=$(( 1 + $(date +%U) - $(date -d "$(date -d "-$(($(date +%d)-1)) days")" +%U) ))
1
Try this:
d=`date +%d` ; m=`date +%m` ; y=`date +%Y` ; cal $m $y | sed -n "3,$ p" | sed -n "/$d/{=;q;}"
Ruy Rocha
- 201
1
simplifying Victor Sanchez's solution:
expr 1 + $(date +%V) - $(date +%V -d $(date +%Y-%m-01))
replace %V with %U if you want weeks starting on Sunday.
btw: had to use expr instead of $((...)) because the later doesn't seem to like numbers with leading zeroes.
faccenda
- 11
0
If you accept external tools in your quest, try dateutils. It's got the notion of occurrence-within-month dates, i.e. 27 Apr 2012 is the 4th Fri in Apr 2012, which just coincides with your week definition. To get that number use:
dconv 2012-04-27 -f %c
=>
04
%c (count) is the format specifier for the occurrence-within the month. Or to be even cooler try
dconv today -f '%cth %a in %b %Y'
=>
1st Wed in Sep 2012
hroptatyr
- 191