Home > Mobile >  Windows batch file to find a word and rename the file
Windows batch file to find a word and rename the file

Time:12-01

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?

CodePudding user response:

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"

CodePudding user response:

There isn't much wrong with your existing method, I'd just use conditional execution instead of error levels:

@For %%G In (PREHA FLAEX PWGEX)Do @%SystemRoot%\System32\find.exe /I "%%G"<"P:\athTo\SALES.csv">NUL 2>&1&&(Ren "P:\athTo\SALES.csv" "SALES%%G.csv")||Echo %%G was not found.>"P:\athTo\log.txt"

If you're not writing the final echo to a file named log.txt change the final "P:\athTo\log.txt" to CON, (or remove >"P:\athTo\log.txt" completely). Please also remember to modify P:\athTo\ as needed

  • Related