I'd like to add an extension to a filename before the file extension, otherwise leaving the given filename the same. In particular, absolute filenames should stay absolute, and relative filenames should stay relative. Examples: suppose the piece I want to insert is ".123"
, then
/home/me/dir/foo.txt
becomes/home/me/dir/foo.123.txt
.xyz.csv
becomesxyz.123.csv
foobar
becomesfoobar.123
(just append in case of no extension)
I don't expect to be dealing with filenames that already have multiple extensions, but just in case, the desired behavior is
nomnom.tar.gz
becomesnomnom.123.tar.gz
I can ensure that the filename does not end with a slash.
The obvious way to do this is by concatenating the directory name, the file base name, the new piece, and the extension:
insertPiece[fn_, piece_] := FileNameJoin[{
DirectoryName[fn],
StringJoin[{FileBaseName[fn], piece, ".", FileExtension[fn]}]
}]
but is there some corner case I missed in which this wouldn't work? Is there a more efficient or more elegant way to do it?
insertPiece[]
won't work nicely on tarballs likestuff.tar.gz
. $\endgroup$ – J. M.'s ennui♦ Jan 23 '12 at 4:49nomnom.123.tar.gz
above, I would considernomnom.123
to be the base filename andtar.gz
to be the extension (I know I have files on my computer that I would want the code to view like this). Without having a list of "valid" file extensions, this would be hard to program in general. $\endgroup$ – Simon Jan 23 '12 at 5:51"."
. The first element of the resulting list is the base filename, and all the rest of the elements in the list are extensions. $\endgroup$ – David Z Jan 23 '12 at 6:05