簡體   English   中英

從Batch變量的文件名中提取節

[英]Extract a section from the filename of a Batch variable

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

我需要從批處理文件中的傳遞參數中提取第一部分。 在這種情況下,它將是“測試123”,但文件始終具有不同的名稱。 “-”必須是定界符(空格+連字符)。

%~n1%1擴展為文件名,但是如何僅指定文件名的一部分?

編輯 :感謝所有的幫助,但只有LotPings的PowerShell解決方案可以按預期工作! 其他人回呼一個空的文件名。 我不知道為什么,但是我確定這與我的設置有關。

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

……還有:

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

此注釋代碼可用於此任務:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM