Search code examples
windowsbatch-filerenamefindstr

Windows batch file to find a word and rename the file


I've been looking through many different posts, but can't find a batch script that works for me. We have an app that only outputs a file called SALES.CSV. This is what one of the lines looks like:

DUNKAN,172225A,11/18/21,2655,11/03/21,11/25/21,1100,"",1,0,"Freight (Distance)",3100,1,-1578.5,FLAEX

Depending on what the last word is, that is what I need the file to be named with. For this line, the file would be renamed to SALESFLAEX.CSV. Their are only a few different words to look for: PREHA, FLAEX and PWGEX. These words will never appear in the same file. So I only need to find the word that currently exists in the file. I did find this code and modified it, but it only works for one file.

findstr /m "FLAEX" SALES.CSV >Nul
if %errorlevel%==0 (
ren SALES.CSV SALESFLAEX.CSV
)

if %errorlevel%==1 (
echo "FLAEX" wasn't found within the Log.txt file!
)
pause

Does anyone have a better method to go about this?


Solution

  • There are a few ways, one being to use a for /F loop to read the file content as a string, then a second for loop to split it by the common delimeter being , and then setting each result as a variable where only the last result will be stored as the final result.:

    @echo off
    for /f "usebackq delims=" %%i in ("SALES.csv") do for %%a in (%%i) do set "last=%%~a"
    ren "sales.csv" "sales%last%.csv"