reddit / emacs

Dumb question? Copying file when target dir contains file with same name

graduale · 2022-02-04 05:01
I’m looking for a way to make a copy a file named “filename.ext” and name it “filename_n.ext”, where n is the smallest integer such that there’s no file in the directory named “filename_n.ext”. The following seems to sort of work, but I’d love to know if there’s a function out there with the right kind of reputation that could do the work without introducing any potential issues: ```elisp (defun my/make-copy (file) (progn (setq new_file file) (setq index 1) (while (file-exists-p new_file) (setq new_file (concat (file-name-sans-extension file) “_” (number-to-string index) "." (file-name-extension file))) (setq index (1+ index))) (copy-file file new_file)) ``` If not, I’d appreciate it if you could let me know whether you know of a better way of doing this. I’m still very much a beginner here… Thanks!
Least_Isopod_4061 · 2022-02-04 05:28
I don't know a function that does that, sorry, but I would use a `let` in your function: (defun my/make-copy (file) (let ((new_file file) (index 1)) (while (file-exists-p new_file) (setq new_file (concat (file-name-sans-extension file) "_" (number-to-string index) "." (file-name-extension file))) (setq index (1+ index))) (copy-file file new_file))
graduale · 2022-02-04 05:52
Oh, right. Makes sense. Thanks!
nv-elisp · 2022-02-04 07:10
> if you could let me know whether you know of a better way of doing this Learn to use version control (e.g. git) and stop backing things up via file name.
nv-elisp · 2022-02-04 07:12
`format` would be better suited than `concat` here.
graduale · 2022-02-04 23:38
I do use git, even if I'm by no means a power user, but I'm not sure this is the best approach for what I'm ultimately trying to do with this little function.
nv-elisp · 2022-02-04 23:56
What is it you're trying to do?
graduale · 2022-02-05 01:51
I’m looking to define a function that will act on a citation key and update the metadata of any associated PDF files using information from the bibtex entry for that key. And it seemed wise to first create a copy of the file in a backup folder before running the command which will call `exiftool` to update the metadata info. Using regular `copy-file` didn’t seem like a good idea since I’d either have to override any older backups of the file or not create any backups if there were older backups with the same file.
nv-elisp · 2022-02-05 02:20
If you're going to copy the file anyhow, you could do it the other way around. Copy the file(s) you're interested in altering to a temp location, run the command on the temp files, if the command is successful, then you replace the originals. If not, then you discard them.
graduale · 2022-02-05 02:51
Thanks for the suggestion! I’ll think about that option.