2

I have two digit month value (01 to 12). I need to get the three letter month abbreviation (like JAN, FEB, MAR etc.) I am able to get it in mixed case using the following command:

date -d "20170711" | date +"%b"

The output is "Jul" I want it to be "JUL". Is there a standard date option to get it?

3
  • 1
    FYI that command probably doesn't do what you think it does (HINT: try date -d "20170611" | date +"%b") Commented Jul 12, 2017 at 1:55
  • @steeldriver, on mobile, can't try, what does? Commented Jul 26, 2017 at 1:43
  • @user1717828 AFAIK the output of the first date command is simply discarded; the second date command prints the current month regardless Commented Jul 26, 2017 at 1:50

5 Answers 5

23
^      use upper case if possible

Result:

$ date +%^b
JUL

Bonus: how I got this answer:

man date Enter /case Enter n

1
  • 1
    Excellent point with using ^! This answer just needs to take into account the variable input of the month number.
    – Jeff Schaller
    Commented Jul 12, 2017 at 2:54
5

You could just pipe it to tr(1):

date -d "20170711" +"%b" | tr '[:lower:]' '[:upper:]'
1
  • for some reason I could not make tr work. But following worked :
    – AlluSingh
    Commented Jul 12, 2017 at 1:40
1

date -d '20170711' '+%^b' and date -d '20170711' '+%b' | tr '[:lower:]' '[:upper:]' works well.

You can also do this using parameter expansion:

$ month=$(date -d '20170711' '+%b')
$ echo "${month^^}"
JUL
0

Since you're dealing with a fairly static piece of information (barring more intercalary events), just use built-in shell commands:

function capdate() {
  case "$1" in
  (01) printf "JAN";;
  (02) printf "FEB";;
  (03) printf "MAR";;
  (04) printf "APR";;
  (05) printf "MAY";;
  (06) printf "JUN";;
  (07) printf "JUL";;
  (08) printf "AUG";;
  (09) printf "SEP";;
  (10) printf "OCT";;
  (11) printf "NOV";;
  (12) printf "DEC";;
  (*)  printf "invalid"; return 1;;
  esac
}

Sample run:

$ m=$(capdate 01); echo $?, $m
0, JAN
$ m=$(capdate Caesar); echo $?, $m
1, invalid

Adjust the text if your locale has different date +%b names.

1
  • +1 if you use an array's indices instead of a case statement :p Commented Jul 12, 2017 at 12:30
0

Another solution, using awk

date -d "20170711" | date +"%b" | awk '{print toupper($0)}'
2
  • why not just tell date to format it in the same command? date -d 20170711 +%b ?
    – Jeff Schaller
    Commented Jul 12, 2017 at 2:07
  • 1
    it's already in 'tr' solution, no need to repeat I thought. Also since author was already on the right track, added what was missing to his command Commented Jul 12, 2017 at 2:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .