从Batch变量的文件名中提取一个部分

时间:2018-06-16 12:19:09

标签: windows batch-file command-line parameter-passing

档案:Test 123 - Test 456 - Test 789.txt

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

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

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

3 个答案:

答案 0 :(得分:1)

使用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

引用args将第二行更改为:

Set "_Args=%~1"

答案 1 :(得分:1)

......另一个:

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

答案 2 :(得分:0)

此评论代码可用于此任务:

@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

由于文件名包含步数,因此必须使用双引号括起文件名来调用此批处理文件,例如:

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 /?