Shell based time and date formatting - can't add in more than a few string literals
I cobbled this together based on the man page, just skimming it though:
$date +'%m.%d.%Y'\ "%r"\ %z 05.03.2015 12:54:11 PM -0700
05.03.2015 12:54:11 PM -0700
which is as close as I can get to what I want:
05.03.2015 - 12:54:11 PM -0700
I can't seem to get the en dash in the middle. I can use a space like I have above if I escape it; looks like a % literal is done by escaping the percent with another percent e.g.: %%
There is a %n for newline, and a very few other modifiers. How do I concatenate the two delimited by a en dash?
And I would love to do this all in the date formatting like I can do in other languages. I really don't want to have to pipe to sed or awk or replace the first space with the " - ".
It's probably best to (single-) quote the entire format string as one, rather than mixing single-quotes, double-quotes and backslash escaping as you have. I certainly think that's the clearest way to write it:
date +'%m.%d.%Y - %r %z'
I'm puzzled you had any problems. Testing on a Mac (10.10.3), I simply included the en-dash in the format string, typing:
$ date +'%m.%d.%Y – %r %z' 05.03.2015 – 04:24:26 PM -0700 $ date +'%m.%d.%Y – %r %z' | utf8-unicode (standard input): 0x30 = U+0030 0x35 = U+0035 0x2E = U+002E 0x30 = U+0030 0x33 = U+0033 0x2E = U+002E 0x32 = U+0032 0x30 = U+0030 0x31 = U+0031 0x35 = U+0035 0x20 = U+0020 0xE2 0x80 0x94 = U+2013 0x20 = U+0020 0x30 = U+0030 0x34 = U+0034 0x3A = U+003A 0x32 = U+0032 0x34 = U+0034 0x3A = U+003A 0x34 = U+0034 0x33 = U+0033 0x20 = U+0020 0x50 = U+0050 0x4D = U+004D 0x20 = U+0020 0x2D = U+002D 0x30 = U+0030 0x37 = U+0037 0x30 = U+0030 0x30 = U+0030 0x0A = U+000A $
I simply included the en-dash in the format string. Now, this is in a UTF-8 terminal, so maybe that accounts for some of the difference. And I happen to know the key sequence for en-dash (–) and em-dash (—) on the Mac keyboard (Option- and ShiftOption-, where - is the 'hyphen-minus' key). If you're not on a Mac, the key sequences will be different.
Note that I avoid having to escape spaces by including them all inside the single quotes around the format string argument. The position of the first quote is 'cosmetic'; the shell removes it whether it is there or date '+%m.…' and date never sees the single quotes.
I managed to get it working. I merely had to escape the spaces, which I tried, but for some reason, didn't work right away. As you will see, it is a mess, which is where I screwed it up. but it works now, and I think it is correct too. I dropped the trailing "g" global modifier as I only wanted the first space edited/altered:
$date +'%m.%d.%Y'\ "%r"\ %z | sed s/\ /\ -\ / >05.03.2015 - 01:06:39 PM -0700
You just need to add the dash - with space immediately after %Y so that it remains inside the quote:
date +'%m.%d.%Y -'\ "%r"\ %z