Search code examples
batch-filebatch-rename

How to clean-up file paths (back/forward slashes) provided as arguments in a .bat script to avoid syntax errors


I have a simple .bat script which renames all files in a folder using ren. The input argument is a path to a folder containing the files to be renamed. The script sometimes returns syntax errors which we've traced to the fact that sometimes the input path has forward slashes, backslashes, or a mix of both (and sometimes starts with a double forward slash). We would like to make this script more robust by allowing it to accept any of these types of paths, and cleaning up the path as part of the .bat script before calling the ren command.

So my question is: is there a (set of) command(s) I can apply to the file path argument (%1 in the example below) before calling the ren function that will correct all forward/backslashes to be consistent and avoid syntax errors? I don't have much experience with .bat scripts, so any code examples would be helpful.

@echo off
setlocal ENABLEDELAYEDEXPANSION
for %%F in (%1*.nc) do (
   for /F "tokens=1-8 delims=_" %%a in ("%%~nF") do (
   ren "%%F" "%%a_%%b_%%c_%%d_%%e_%%g_%%f_%%h.nc"
   ) 
) 

UPDATE: In the end, only the last suggestion by Magoo was needed, because changing %1 to "%~f1" fixed the slash issues. I also had to add %~f1\ to the first argument of the ren command because otherwise it was somehow looking in the wrong folder (the first for found the files ok, but the ren command was looking in the wrong folder.

@echo off
setlocal ENABLEDELAYEDEXPANSION
for /F "delims=" %%F in ('dir /b /a-d "%~f1\*.nc"') do (
   for /F "tokens=1-8 delims=_" %%a in ("%%~nF") do (
   ren "%~f1\%%~nF.nc" "%%a_%%b_%%c_%%d_%%e_%%g_%%f_%%h.nc"
   ) 
) 

Solution

  • set "corrected=%~1"
    set "corrected=%corrected:/=\%"
    

    Then use %corrected% in place of %1 AND quote the filename thus:

    for %%F in ("%corrected%*.nc") do (
    

    If %1 is always a directory-name, then add

    if "%corrected:~-1%" neq "\" set "corrected=%corrected%\"
    

    as a third set line before the for line.

    The first set assigns the value of %1 to a variable corrected - the ~ removes any enclosing quotes.

    The second set changes all strings matching that between the : and = into that between the = and % in the variable given and assigns to the first-mentioned variable (can be the same variable, as in this case)

    The third set, if used, checks that the last character is \ and if it is not, appends a \.

    The quoting of the filename-string allows there to be spaces in the path/filename and is harmless if there are no spaces.

    To avoid attempting to rename a file twice, instead of

    for %%F in ("%corrected%*.nc") do (
    

    use

    for /F "delims=" %%F in ('dir /b /a-d "%corrected%*.nc"') do (
    

    This builds a list of filenames in memory, then processes that list.