首页 > 解决方案 > Set command gives error when trying parameter expansion to replace characters

问题描述

I'm new to batch scripting and cannot figure out why this isn't working since I took it almost verbatim from another post that says it works. Except in the Post they're replacing underscores "_" with a space " ".

My goal is to replace any underscores "_" in a filename with a dash "-".

@echo off
Setlocal enabledelayedexpansion

SET SRC_FOLDER=C:\test_src
SET EXT=txt

for %%a in (%SRC_FOLDER%\*_*.%EXT%) do (
    set "filename=%%a"
    set "!filename!" "!filename:_=-!"
    echo Filename = !filename!
)

I get the following errors:

C:\Scripts>test_script.bat
Environment variable C:\test_src\Underscore_1.txt" not defined
Filename = C:\test_src\Underscore_1.txt
Environment variable C:\test_src\Underscore_2.txt" not defined
Filename = C:\test_src\Underscore_2.txt

Any idea what is wrong with that set command. I usually use Bash scripting, but have no choice in this case but to use Batch, so I'm not sure what's wrong here...

----EDIT----

I also added another FOR loop, which I'm sure could be done within just one loop, but since I'm not familiar with the complexities of batch, I did it in its own. In the second loop I'm renaming ALL files in the directory by adding a Prefix to each filename, adding a timestamp. But, it appears that when it renames the files, one of the files is getting the Prefix added twice. Any idea why this is?

Here is the full code and the output:

@echo off
Setlocal enabledelayedexpansion

SET "SRC_FOLDER=C:\test_src"
SET "EXT=txt"
SET "TIMESTAMP=Scan-%date:~4,2%%date:~7,2%%date:~10,4%-%time:~0,2%%time:~3,2%%time:~6,2%%time:~9,2%"

REM echo %TIMESTAMP%

for %%a in ("%SRC_FOLDER%\*_*.%EXT%") do (
    Set "filename=%%~na"
    Ren "%%a" "!filename:_=-!%%~xa"
)

for %%f in ("%SRC_FOLDER%\*.%EXT%") do (
    set "newfilename=%TIMESTAMP%-%%~nf%%~xf"
    echo New Name = !newfilename!
    Ren "%%f" "!newfilename!"
)

The strange thing is, it's only doing this to the first file it renames. If I rename the first file that it's doing this to so that is no longer the first file, it then does it to the next. i.e. renaming File1.txt to File5.txt, it then renames File2.txt twice. Am I missing something?

OUTPUT:

C:\Scripts>test_script.bat
New Name = Scan-10182019-13552864-File1.txt
New Name = Scan-10182019-13552864-File2.txt
New Name = Scan-10182019-13552864-File3.txt
New Name = Scan-10182019-13552864-File4.txt
New Name = Scan-10182019-13552864-Scan-10182019-13552864-File1.txt
New Name = Scan-10182019-13552864-Under-score-2.txt
New Name = Scan-10182019-13552864-Underscore-1.txt

标签: batch-file

解决方案


看起来你的双引号有一些问题。

@Echo Off
SetLocal EnableDelayedExpansion

Set "SRC_FOLDER=C:\test_src"
Set "EXT=txt"

For %%a In ("%SRC_FOLDER%\*_*.%EXT%") Do (
    Set "filename=%%~na"
    Ren "%%a" "!filename:_=-!%%~xa"
)

推荐阅读