8

I would like to highlight today's date in the output of the cal command. What is the best way?

This is what I have so far:

cal -m | grep -C6 --color "$(date +%e)"

but it doesn't work for all cases e.g, when the date has a single digit. I also want the highlighting to work when I display the calendar for a year.

dogbane
  • 29,087
  • 16
  • 80
  • 60

7 Answers7

12

I don't know how to highlight the day in the year calendar cal -y with just regular expressions, but the reason your example was not working for single digit dates is because $(date +%e) prepends a space to the output when the date has a single digit.

This will work:

cal | grep --color -EC6 "\b$(date +%e | sed "s/ //g")"
Jorge Bucaran
  • 437
  • 4
  • 13
  • 2
    in __fish__: `cal | grep --color -EC6 "\b"(date +%e | sed "s/ //g")` – Jorge Bucaran Feb 17 '15 at 01:42
  • 1
    The command should be `cal | grep --color -EC6 "\b$(date +%e | sed 's/ //g')\b"` instead, otherwise, if the day of month is 1 or 2 there will be multiple 1x and 2x days get highlighted. – xpt Sep 13 '21 at 20:16
4

ncal -b scratched this itch for me.

3

On my system (openSUSE 11.4, util-linux-2.19), the current date in output form cal is automatically highlighted (reverse colors) if the output goes to terminal. As per the manpage, this seems to be the default. If it does not work on your system, it might be a bug.

Petr Uzel
  • 7,157
  • 4
  • 30
  • 26
3

The output is already highlighted, so you don't need to highlight it manually. In case you want it to work with grep, you need to disable it:

cal -mh | grep -C6 --color "$(date +%e)"
Braiam
  • 35,380
  • 25
  • 108
  • 167
  • `cal | grep -C6 --color "\b$(date +%e)\b"` ... need the boundary `\b` otherwise it will highlight chunks of the year too – slf Oct 14 '14 at 13:21
1

It may be fairly complicated to do something like this;
Why not try something like pal?

Chris2048
  • 601
  • 2
  • 6
  • 11
0

I think you can use the command date +%-e instead of date +%e to remove the space.

Celada
  • 43,173
  • 5
  • 96
  • 105
0

For BSD systems without grep --color option:

B=$(tput bold)
U=$(tput sgr0)
DAY=$(date +%e | tr -d " ")
cal | sed -E -e "s|(.*[^0-9])($DAY)([^0-9].*)|\1$B\2$U\3|"

Oneliner:

cal | sed -E -e "s|(.*[^0-9])($(date +%e | tr -d " "))([^0-9].*)|\1$(tput bold)\2$(tput sgr0)\3|"

With week numbers left side:

cal -m -w | sed -E -e "s|(.*) ([[ 0-9]+])$|\2 \1|" -e "1,2s|^|     |" -e "s|(.*[^0-9])($(date +%e | tr -d " "))([^0-9].*)|\1$(tput bold)\2$(tput sgr0)\3|"