代码之家  ›  专栏  ›  技术社区  ›  Clacers

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

  •  0
  • Clacers  · 技术社区  · 8 年前

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

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

    %~n1 扩大 %1 只指定文件名,但如何只指定文件名的一个部分?

    编辑 :感谢您提供的所有帮助,但只有lotpings的powershell解决方案才能按预期工作!其他人回显一个空文件名。我不知道为什么,但我肯定这和我的设置有关。

    3 回复  |  直到 8 年前
        1
  •  1
  •   LotPings    8 年前

    另一个使用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
    

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

    Set "_Args=%~1"
    
        2
  •  1
  •   Compo    8 年前

    还有一个:

    @Echo Off
    Set "filename=%~n1"
    Set "newname=%filename: -="&:"%"
    Echo "%newname%%~x1"
    Pause
    GoTo :EOF
    
        3
  •  0
  •   Mofi    8 年前

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

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