• Forum
  • Lounge
  • I need a batch script or powershell comm

 
I need a batch script or powershell command

I have a folder with a bunch of files and subfolders in it. I need to delete all files in this folder that have filenames matching files in any of the subfolders.

Can anyone help me out?
A quick O(n²) solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@echo off
for %%F in (*) do (
  for /R . %%D in (*) do (
    if %%~nxF==%%~nxD (
      if not %%~dpF==%%~dpD (
        if exist %%~dpnfF (
          echo deleting %~nxF
          del /f/q %%~dpnxF
        )
      )
    )
  )
)
echo done

for every file name in this folder
  for every file name in this and all subfolders
    if the simple names match
      if the paths don't match (ie. it isn't a file in this folder)
        if the file still exists
          tell the user we're deleting it
          and delete it





tell the user we're done

It requires command extensions. A much more elegant solution is possible, but this is all you're gonna get from me right now.

Hope this helps.
Ugliest python implementation I could think of.

1
2
3
4
5
6
import os
from os import walk
from os import join
from os.path import isfile
rootDir = "" #assign root directory
for j in [g for g in [f for _, _,files in walk(rootDir) for f in files] if [f for _, _,files in walk(rootDir) for f in files].count(g) > 1 and isfile(join(rootDir,g))]: os.remove(join(rootDir, j))


edit: made it worse. Donn't know if this will work either.
Last edited on
Linux:

1
2
3
#!/bin/bash
#(sudo optional if the folder is not owned by power-user)
sudo rm -rf $1


I am not responsible for accidental erasure of your HDD.
Last edited on
That deletes folders -- not what OP wants.
Also, OP is asking for Windows systems...
Thanks guys. That FOR command did the trick.
What is the point of a script that does nothing but call another program? Instead of "./my-script dir" you could just type "rm -rf dir" yourself.

Here's my solution: find "$directory" -type f -name '$pattern' -delete

This one is also not for Windows (unless you have Cygwin) but there may be a Windows equivalent.
Does version control matter here? Or are we positive that all similarly named files contain the same data?
I can't draw any conclusions other than what the OP posted.

Personally, I would be loathe to delete a file that has been touched more recently than its 'duplicate'. It might be worth putting a condition in for that.

But that may be a moot point. I assume that it isn't an issue or OP would have said something about it.
Topic archived. No new replies allowed.