6

I have been trying to:

cp file.csv file.$(date +%D).csv

But it fails because the filenames is: file.03/27/19.csv with the slash of separate directories.

And I have been trying again to:

cp file.csv file.$(printf "%q" $(date +%D)).csv

But it still fails.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
tres.14159
  • 234
  • 1
  • 2
  • 6
  • You can not set a filename with slash characters: https://stackoverflow.com/questions/9847288/is-it-possible-to-use-in-a-filename – tres.14159 Mar 27 '19 at 17:31
  • the problem is your use of the `date` format using the `/` character. You said it yourself, the shell is seeing them as directory markers. Try one of the many other options available from `date`. You might be able to get the / escaped so the filename uses the character code (like putting a space in a filename), but that is often problematic. – 0xSheepdog Mar 27 '19 at 17:32

1 Answers1

19

You can't have / (byte 0x2F on ASCII-based systems) in a file name, period.

You can use characters that look like / like (U+2215 division slash) or (U+2044 fraction slash though found in fewer of the charsets used in current locales), so you could do (provided that U+2215 character exists in the locale's charset, includes GBK, BIG5, UTF-8, GB18030):

cp file.csv "file.$(date +%D | sed 's|/|∕|g').csv"

Or with some shells (zsh, bash at least):

cp file.csv "file.$(date +%D | sed $'s|/|\u2215|g').csv"

(here using sed instead of tr as some tr implementations including GNU tr still don't support multi-byte characters).

But you may run into problems like the file name being rendered differently in locales using a different charset from the one that was in use at the time you created the file (and of course the confusion of users when they see what looks like a slash in a file name).

My advice would be to use the standard non-ambiguous (for most people outside the US, 03/12/18 would be interpreted as the 3rd of December 2018 for instance) YYYY-mm-dd format instead (which also helps wrt sorting):

cp file.csv "file.$(date +%Y-%m-%d).csv"

Which with many date implementations you can shorten to:

cp file.csv "file.$(date +%F).csv"
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501