相关:
How to list the elements of the path in a batch file?
How does FOR work?
您将如何编写批处理文件或 CMD 文件来从路径中删除元素?它应该优雅地处理:
- 大小写差异
- 简称和长名
我已经使用 tr.exe 完成了此操作,但它速度慢且复杂,并且使用临时文件,这使得它变得更加复杂。
我认为答案是这样的:
setlocal
set tpath=""
set _path="%PATH:;=" "%"
for %%p in (%_path%) do (
call :KeepIfNotEqual %%p %elementToRemove%
)
endlocal & set path=%tpath%
...其中 %elementToRemove% 是要删除的路径元素。 KeepIfUnique 必须是一个带有两个参数的子例程 - 目录名称,对它们进行规范化,并将第一个参数附加到 tpath,如果它不等于第二个参数 (elementToRemove)。
正如我所说,我可以使用 tr.exe 执行此操作,但我可以仅使用 Windows cmd.exe shell 中的内置命令来执行此操作吗?
编辑:我想当您认真对待它时,问题是,如何在 cmd.exe 中进行大小写转换?
最佳答案
这是我根据 Igor 的提示想出的。
@echo off
goto START
-------------------------------------------------------
rmpath.bat
remove a path element from path
Created Tue Sep 15 21:33:54 2009
-------------------------------------------------------
:START
SETLOCAL ENABLEDELAYEDEXPANSION
@REM require one argument (the path element to remove)
if _%1==_ goto USAGE
@REM ~fs = remove quotes, full path, short names
set fqElement=%~fs1
@REM convert path to a list of quote-delimited strings, separated by spaces
set fpath="%PATH:;=" "%"
@REM iterate through those path elements
for %%p in (%fpath%) do (
@REM ~fs = remove quotes, full path, short names
set p2=%%~fsp
@REM is this element NOT the one we want to remove?
if /i NOT "!p2!"=="%fqElement%" (
if _!tpath!==_ (set tpath=%%~p) else (set tpath=!tpath!;%%~p)
)
)
set path=!tpath!
@call :LISTPATH
goto ALL_DONE
-------------------------------------------------------
--------------------------------------------
:LISTPATH
echo.
set _path="%PATH:;=" "%"
for %%p in (%_path%) do if not "%%~p"=="" echo %%~p
echo.
goto :EOF
--------------------------------------------
--------------------------------------------
:USAGE
echo usage: rmpath ^<arg^>
echo removes a path element from the path.
goto ALL_DONE
--------------------------------------------
:ALL_DONE
ENDLOCAL & set path=%tpath%
关于windows - 您将如何编写 .bat 或 .cmd 文件以从 PATH 中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1429988/