我有以下內容,它將檔案夾名稱 (FOLDER) 縮減為僅在第一個空格 (tmpFOLDER) 之前的所有文本。
@echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "%~dp0" || exit /B
for %%I in (..) do set "FOLDER=%%~nxI"
for /f "tokens=1 delims= " %%a in ("%FOLDER%") do set tmpFOLDER=%%a
ECHO %FOLDER%
ECHO %tmpFOLDER%
popd
endlocal
主要要求:
有沒有辦法反過來做到這一點?
檔案夾名稱 (%FOLDER%):Smith - John
當前示例 (%tmpFOLDER%):Smith
所需示例 (%tmpFOLDER%):John
中學:
有沒有辦法對檔案執行此操作,而不考慮任何檔案型別(即 .txt)?
檔案名 (%FILE%): "Smith - John.txt"
當前示例 (%tmpFILE%):Smith
所需示例 (%tmpFILE%):John
uj5u.com熱心網友回復:
該for /F環可以不從字串中提取的結束計數令牌。但是,您可以使用標準for回圈遍歷檔案或目錄名稱的單詞:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Retrieve base name of grand-parent directory of this script:
for /D %%I in ("%~dp0..") do set "FOLDER=%%~nI"
echo Old name: "%FOLDER%"
set "PREV=" & set "COLL="
rem /* Unnecessary loop iterating once and returning the whole directory name;
rem it is just here to demonstrate how to handle also more than one names: */
for /F "delims= eol=|" %%L in ("%FOLDER%") do (
rem // Store current name strng and reset some interim variables:
set "NAME=%%L" & set "PREV=" & set "COLL= "
rem // Toggle delayed expansion to avoid issues with `!` and `^`:
setlocal EnableDelayedExpansion
rem // Ensure to have each space-separated word quoted, then loop through them:
for %%K in ("!NAME: =" "!") do (
rem /* Build new buffer by concatenating word from previous loop iteration,
rem then transfer it over `endlocal` barrier (localised environment): */
for %%J in ("!COLL! !PREV!") do (
rem // Store current word in an unquoted manner:
endlocal & set "ITEM=%%~K"
rem // Store current buffer, store current word for next iteration:
set "COLL=%%~J" & set "PREV=%%~K"
setlocal EnableDelayedExpansion
)
)
endlocal
)
rem // Retrieve final result:
set "RESULT=%COLL:~3%"
echo New name: "%RESULT%"
echo Last word: "%PREV%"
endlocal
exit /B
此方法回傳洗掉了最后一個單詞的名稱以及名稱的最后一個單詞。
另一種解決方案是有時所謂的代碼注入技術,它需要延遲變數擴展并且很難理解:
setlocal EnableDelayedExpansion
echo Old name: "%FOLDER%"
set "RESULT=%FOLDER: =" & set "RESULT=!RESULT!!ITEM!" & set "ITEM= %"
echo New name: "%RESULT%"
echo Last word: "%ITEM:* =%"
endlocal
請注意,當輸入字串包含!, ^or時,這將失敗"(但后者無論如何都不會出現在檔案或目錄名稱中)。
另一種方法是替換空格\,然后(錯誤)使用~-modifiers,這是因為純檔案或目錄名稱不能單獨包含\:
echo Old name: "%FOLDER%"
rem // Precede `\` to make pseudo-path relative to root, then replace each ` ` by `\`:
for %%I in ("\%FOLDER: =\%") do (
rem // Let `for` meta-variable expansion do the job:
set "RESULT=%%~pI"
set "LAST=%%~nxI"
)
rem // Remove leading and trailing `\`; then revert replacement of ` ` by `\`:
set "RESULT=%RESULT:~1,-1%"
echo New name: "%RESULT:\= %"
echo Last word: "%LAST%"
這種方法甚至不需要延遲擴展。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/408202.html
標籤:
上一篇:Shell腳本:單引號轉義
下一篇:在批處理腳本中修剪GUID
