Penny
Penny

Reputation: 816

Compare file name if exists then delete using batch file

I have lots of .csv files in a folder by names like TOP_QUERIES-filename.com.csv, TOP_QUERIES-www.filename.com.csv Is it possible to compare all the file names except TOP_QUERIES-www. to find if TOP_QUERIES-www.filename.com.csv exists then delete it otherwise keep them.

I know its possible in php but i want to get it done using batch file

Thankyou

Upvotes: 1

Views: 903

Answers (1)

MC ND
MC ND

Reputation: 70923

@echo off
    setlocal enableextensions disabledelayedexpansion

    pushd "c:\target\folder" && (
        for /f "tokens=1,* delims=." %%a in ('
            dir /a-d /b "TOP_QUERIES-www.*.csv"
        ') do echo del /q "TOP_QUERIES-%%b" 2>nul
        popd
    )

This changes the current active directory to the one containing the files and for each www prefixed one, tries to delete the corresponding paired file. If it does not exist, the error is discarded. At the end, the current active directory is restored

To detemine the name of the file to delete, a for /f is used to tokenize the file name using dots as delimiters. We request two tokens (tokens=1,*), the first token precedes the first delimiter and is stored in the %%a replaceabe parameter while the second token requested is the rest of the file name and is stored in the %%b (the next one alphabetically) replaceable parameter.

Delete operations are only echoed to console. If the output is correct, remove the echo command before the del

Upvotes: 2

Related Questions