How to use the symbol %, &, = in batch files?

后端 未结 1 987
囚心锁ツ
囚心锁ツ 2021-01-26 10:58

This is the batch file I wrote to rename files. The problem I get is that if the file name includes one of the following symbol, the script does not work. % &

相关标签:
1条回答
  • 2021-01-26 11:09

    The following example shows you how to work the character substitution.
    Please just open cmd instead of clicking on batch-file, navigate in the directory where is your script and run the script.

    @echo off
    setlocal
    
    set "mydir=%USERPROFILE%\Desktop"
    pushd %mydir%
    
    REM creating some empty files with space in file name
    REM Here, you must escape the character '%' by doubling.
    REM _somefile with % .txt
    copy nul "_somefile with %%  &  =  21 .txt"
    copy nul "_somefile with %%  &  =  22 .txt"
    copy nul "_somefile with %%  &  =  23 .txt"
    
    
    setlocal enabledelayedexpansion
    for /f "delims=" %%i in ('dir _somefile*with*.txt /s /B') do (
        set "newname=%%~nxi"
        echo REN "%%i" "!newname: =!"
    )
    endlocal
    popd
    pause
    exit /b 0
    

    Note I added an instance pause.

    Output:

    REN "_somefile with %  &  =  21 .txt" "_somefilewith%&=21.txt"
    REN "_somefile with %  &  =  22 .txt" "_somefilewith%&=22.txt"
    REN "_somefile with %  &  =  23 .txt" "_somefilewith%&=23.txt"
    

    Edit: I updated the example with the characters that you mentioned.

    0 讨论(0)
提交回复
热议问题