0

I want to develop batch having step that it will update timestamps of all files within some directory. Below command gives list of all files in directories. Can we redirect output of this command to some other windows equivalent touch command, so as to update the timestamps for all files?

cmd>dir /B
Log_adminUser_1.log
Log_adminUser_2.log
Log_adminUser_3.log
Log_adminUser_4.log
Log_adminUser_5.log
Log_adminUser_6.log
novice
  • 53
  • 9
  • Quick-and-easy method: use batch to rename the files as YYMMDD_HHMMSS_originalfilename. Sure, their timestamps won't be updated, but the names would then be listed in date-order. – Magoo Jan 21 '21 at 04:11
  • This question has been asked and answered several times on StackOverFlow. Please consider searching and reading before posting questions. – Squashman Jan 21 '21 at 15:06
  • Thanks for your suggestion, I will try to search until I find it. However I wanted to have some way to touch all files in certain directory. I posted question specific to this query. I think answer posted here by @reinier quite helpful to create alternative touch utility in batch. – novice Jan 22 '21 at 00:39

1 Answers1

1

As a trick for touching all files in a directory, you could use this:

@ECHO OFF
FOR /F "delims=" %%G IN ('DIR /B') DO (
  COPY /B "%%G"+,, "%%G" > NUL
)

The COPY /B construct is documented in TOUCH on SS64, which also explains some caveats with it.

Reinier Torenbeek
  • 16,669
  • 7
  • 46
  • 69
  • Quote filenames for names containing separators, etc? – Magoo Jan 21 '21 at 04:39
  • Good point -- I think it works for the single `touch` script but let me see if I can fix that loop... – Reinier Torenbeek Jan 21 '21 at 04:44
  • OK, I believe that is fixed now. Anything else I overlooked? (Found the correction [here](https://stackoverflow.com/questions/5553040/batch-file-for-loop-with-spaces-in-dir-name)) – Reinier Torenbeek Jan 21 '21 at 04:50
  • Well, actually - `>nul` will not hide errors; you need `2>nul` for that. Try making the file read-only for a test. – Magoo Jan 21 '21 at 04:55
  • That is interesting: the message "The system cannot find the file specified." is actually suppressed via `> nul` so that one must be on stdout. Apparently it is not considered an error. However, "Access is denied." is on stderr, like you pointed out -- thanks. The former message will no longer appear with that earlier correction, so any relevant errors are not suppressed indeed, which is a good thing. – Reinier Torenbeek Jan 21 '21 at 05:01
  • 1
    I'm not the downvoter, BTW - but I object to your "single file" solution. Suppose `%1` (which *could* be quoted as `"%~1"`) contains `?` or `*` - how much chaos could that cause? – Magoo Jan 21 '21 at 05:09
  • That single file thing did not add much anyway so I have removed that for now, until I understand what those globbing characters could cause. Strangely, it seemed to work OK with just `*`. – Reinier Torenbeek Jan 21 '21 at 05:20