从批处理变量的文件名中提取节



文件:Test 123 - Test 456 - Test 789.txt

我需要从批处理文件中传递的参数中提取第一部分。在这种情况下,它将是"Test 123",但文件始终具有不同的名称。"-"需要是分隔符(空格 + 连字符(。

%~n1

仅将%1扩展到文件名,但如何仅指定文件名的一部分?

编辑:感谢您的所有帮助,但只有LotPings的PowerShell解决方案可以按预期工作!其他人回显了一个空文件名。我不知道为什么,但我确信这与我的设置有关。

...另一个:

@Echo Off
Set "filename=%~n1"
Set "newname=%filename: -="&:"%"
Echo "%newname%%~x1"
Pause
GoTo :EOF

另一种使用PowerShell的解决方案

@Echo off
For /f "delims=" %%A in ('
Powershell -NoP -C "('%~1' -Split ' - ')[0]"
') Do Set "NewName=%%A%~x1"
Set NewNAme

>  SO_50887843_2.cmd " -;Test 123 - Test 456 =! Test 789.txt"
NewName= -;Test 123.txt

使用字符串替换,您可以进行一些随机处理(使用不带引号的参数(

:: SO_50887843.cmd
@Echo off
Set "_Args=%*"
:: remove content up to first delimiter " - "
Set "_Rest=%_Args:* - =%"
:: remove " - " and Rest from Args
Call Set "_First=%%_Args: - %_Rest%=%%"
Set _

> SO_50887843.cmd Test 123 - Test 456 - Test 789.txt
_Args=Test 123 - Test 456 - Test 789.txt
_First=Test 123
_Rest=Test 456 - Test 789.txt

带引号的参数将第二行更改为:

Set "_Args=%~1"

此注释代码可用于此任务:

@echo off
if "%~1" == "" goto :EOF
setlocal EnableExtensions DisableDelayedExpansion
rem Get file name without extension and path assigned to an environment variable.
set "FileName=%~n1"
rem For file names starting with a dot and not having one more dot like .htaccess.
if not defined FileName set "FileName=%~x1"
rem Exit the batch file if passed argument is a folder path ending with a backslash.
if not defined FileName goto EndBatch
rem Replace each occurrence of space+hyphen+space and next also of just
rem space+hyphen by a vertical bar in file name. A vertical bar is used
rem because a file name cannot contain this character.
set "FileName=%FileName: - =|%"
set "FileName=%FileName: -=|%"
rem Get first vertical bar delimited string assigned to the environment variable.
for /F "eol=< delims=|" %%I in ("%FileName%") do set "FileName=%%I"
echo First part of "%~nx1" is "%FileName%".
rem Add here more commands using the environment variable FileName.
:EndBatch
endlocal

必须使用用双引号括起来的文件名调用此批处理文件,因为文件名包含 pace,例如:

GetFirstFileNamePart.bat "Test 123 - Test 456 - Test 789.txt"

这个批处理文件甚至可以使用以下非常奇怪的文件名调用它:

GetFirstFileNamePart.bat " - Test 123 -Test 456 != Test 789 & More.txt"

在这种情况下,输出是:

First part of " - Test 123 -Test 456 != Test 789 & More.txt" is "Test 123".

要了解使用的命令及其工作原理,请打开命令提示符窗口,在那里执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。

  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rem /?
  • set /?
  • setlocal /?

最新更新