[one-liner]: Making the Linux date Command Display the Month & Day in Single Digits

Background

Anyone that’s worked in a UNIX environment is probably somewhat familiar with the date command. Up until recently I had no reason to go beyond the typical use cases like the following:

1
2
3
4
5
6
7
# locale's date & time
% date +%c
Fri 22 Jul 2011 10:22:29 PM EDT
 
# full date
% date +%F
2011-07-22

However, the problem came up where I needed dates in these kinds of formats:

  • 2011.7.2
  • 2011.7.12
  • 2011.10.2
  • 2011.10.12

Basically I needed to drop any leading zeros, and show the month/day in single digit form. Turns out this is easy to accompish with the date command too, it’s just not that obvious. So here’s how!

Solution

When in doubt, always try and refer to a command’s man pages 8-). In this case date’s man page tells you how to do this. The key? Using flags to the ‘%’ fields. The flags augment the formatting of date’s output. Here’s an excerpt from the man page that shows all the flags:

1
2
3
4
5
6
7
8
9
10
11
12
By default, date pads numeric fields with zeroes.  The following optional 
flags may follow `%':
 
-      (hyphen) do not pad the field
 
_      (underscore) pad with spaces
 
0      (zero) pad with zeros
 
^      use upper case if possible
 
#      use opposite case if possible

The key line is the one that mentions not padding the field using a hyphen. By including a hyphen after the percent we can instruct the date command not to pad the output like so:

1
2
3
4
5
6
7
8
9
10
11
# ex1. output without leading zeros
% date +%Y.%-m.%-d
2011.7.22
 
# ex2. output without leading zeros
% date +%Y.%-m.%-d
2011.7.2
 
# ex3. output without leading zeros
% date +%Y.%-m.%-d
2011.10.2

Some of the other flags might be useful too. Here are some more examples using date’s other flags:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# ex1. upper case day of week
% date +%a
Fri
% date +%^a
FRI
% date +%A
Friday
% date +%^A
FRIDAY
 
# ex2. lower case time zone
% date +%Z
EDT
% date +%#Z
edt
 
# ex3. upper case locale's date & time
% date +%c
Fri 22 Jul 2011 10:22:29 PM EDT
% date +%^c
FRI 22 JUL 2011 10:21:16 PM EDT
 
# ex4. pad with a leading space
% date +%m
07
% date +%_m
 7
% date +%d
23
% date +%_d
23
% date +%d
03
% date +%_d
 3

References

NOTE: For further details regarding my one-liner blog posts, check out my one-liner style guide primer.

This entry was posted in linux, one-liner, shell, Syndicated, tips & tricks. Bookmark the permalink.

Comments are closed.