Home > other >  Given text file with names, if folder has files with such names - delete it, else make folder with t
Given text file with names, if folder has files with such names - delete it, else make folder with t

Time:09-30

I was curious to make a script in windows cmd that is taking source.txt file with such names:

User1
User2
User3
User4
User5
User6

Secondly, I have created the destination folder F:\Destination The task is to iterate with source.txt and if a file from this txt exists at the address F:\Destination, delete it, if such file does not exist, create a folder with this name.

For example: I have User1.txt User2.txt and User3.txt in F:\Destination and I need to delete them and create folders User4 User5 and User6

Here is my script, but sadly it's doing nothing

for /F "usebackq eol=| delims=" %G in ("source.txt") do if exist
"Destination\%~G" del "Destination\%~G" if not exist "Destination\%~G" md "Destination\%~G"

Hope to get some advice, thanks!

CodePudding user response:

For /F "usebackq delims=" %%G in ("source.txt") do (
 if exist "Destination\%%~G.txt" del "Destination\%%~G.txt" 
 ) else (md "Destination\%%~G")

This assumes that your code forms part of a batch file.

Since source.txt contains the names without the extension .txt, you need to add the extension in.

Note that if the file does not exist, but the directory already exists, you'll get an error (directory already exists) which you can suppress by appending 2>nul to the md command (within the parentheses)

You should also note that running the job a second time will create the directory since the first run will have deleted the file.

  • Related