【问题标题】:Replace part of one string variable with another in a batch file在批处理文件中将一个字符串变量的一部分替换为另一个
【发布时间】:2013-11-06 08:48:03
【问题描述】:

我正在尝试对目录(及其子目录)中的所有文件运行命令,但正在努力为我找到的文件生成相对路径。

我的代码是……

@echo off

set currentDir=%~dp0

for /r %%f in (*.js) do (
    echo %currentDir%
    echo %%f

    set relativePath=%%%f:%currentDir%=%
    echo %relativePath%
)

基本上,如果我在 C:\somedir 中运行脚本并找到 C:\somedir\anotherdir\file.js 我需要 %relativePath% 仅包含 另一个目录\file.js

请帮忙!

【问题讨论】:

    标签: windows batch-file


    【解决方案1】:

    EDITED - 适应所需的输出。

     @echo off
    
        setlocal enableextensions enabledelayedexpansion
    
        rem to take batch file directory as current directory
        set "currentDir=%~dp0"
    
        rem OR to take current directory as current directory
        set "currentDir=%cd%"
    
        rem Select only one of the above
    
        rem add trailing backslash if not present
        if not "%currentDir:~-1%"=="\" set "currentDir=%currentDir%\"
    
        rem Do recurse directory
        for /r %%f in (*.js) do (
            set "relativePath=%%f"
            set "relativePath=!relativepath:%currentDir%=!"
            echo %relativePath%
        )
    

    【讨论】:

    • +1,但我喜欢使用setlocal 时的endlocals :-)。它更整洁。
    • @npocmaka:我同意。我没有包括它认为批处理文件将需要更多内容。无论如何,endlocal 是隐式的,并且在批处理文件执行结束时,任何挂起的 setlocal 都会被取消。仅当您需要确保在发出 setlocal 后,对环境变量的更改仍然存在时,它才是强制性的。但是,是的,我更喜欢平衡代码。
    猜你喜欢
    • 1970-01-01
    • 2021-03-02
    • 2011-03-25
    • 2012-08-18
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多