-1

I have been unable to find a solution to my problem with Google, I was wondering if anyone can give any advice.

I have a folder full of files looking like this:

device1_ip_1234asdf.txt
device1_stats_1234asdf.txt
device1_ip_1234asdf2.txt
device1_stats_1234asdf2.txt
device2_ip_1234asdf.txt
device2_stats_1234asdf.txt
device2_ip_1234asdf2.txt
device2_stats_1234asdf2.txt

...etc

where there are multiple log files downloaded of different types for different devices.

I only need the latest log files for each device, so after processing the folder should look like this:

device1_ip_1234asdf.txt
device1_stats_1234asdf.txt
device2_ip_1234asdf.txt
device2_stats_1234asdf.txt

There is no way to tell the latest files from the file name, it has to be determined from the date modified tag.

I need to write a script that basically goes:

get list of files for device1, log type ip
del device1_ip* where file is not latest
get list of files for device1, log type stats
del device1_stats* where file is not latest
repeat for device2, device3, etc

Can anyone point me in the right direction? I'm sure I could do this easily with bash, but windows batch files have me stumped.

I have struggled to find a way to just populate an array of file names.

Aacini
  • 65,180
  • 12
  • 72
  • 108
  • I've had a look at that one, it is almost a solution except it would only work for one device. Device1 may have more newer files than Device2, so the solution there would still keep older log files for certain devices, while removing the latest for others. But... I just saw a possible alternative, will test. – averagescripter May 31 '16 at 00:35

2 Answers2

0
@echo off
setlocal

rem Process all files, latest first
for /F "tokens=1,2* delims=_" %%a in ('dir /A:-D /O:-D /B *.txt') do (
   rem If this file is the latest of this device_type
   if not defined file[%%a_%%b] (
      rem Keep it
      set "file[%%a_%%b]=1"
   ) else (
      rem Delete it
      ECHO del "%%a_%%b_%%c"
   )
)
Aacini
  • 65,180
  • 12
  • 72
  • 108
0

Thank you for your suggestions,

I ended up sorting it using a modification of the line in the problem noted above, Batch file that keeps the 7 latest files in a folder.

for /f "skip=1 eol=: delims=" %%F in ('dir /b /o-d device1*ip*.txt') do @del "%%F"

By targeting specific files instead of the whole group, I am now removing all the older log files.

Thanks!

  • This method requires that you hard-code each device_type pair. See [my solution](http://stackoverflow.com/questions/37535023/batch-script-to-delete-non-latest-files/37535429#37535429) – Aacini May 31 '16 at 01:26