2017-02-22 61 views
0

我在寫一個簡單的批處理文件來創建新的用戶定義的文件。 我的問題是如何接受有或沒有句點的擴展名的輸入,並且不會產生雙重句點(即name1..txt)。 我也想避免必須打印說明,以便包括/不包含它。感謝您的幫助!如何基於變量子串的存在條件語句

我的方法如下。我想在「擴展」變量ext的開頭尋找一段時間,然後運行相應的FOR循環來創建文件。

setlocal enabledelayedexpansion 
set num= 
set name= 
set ext= 

:setnum 
set /P "num=Number of files to create?: " 
If not defined num Echo.&Echo You must enter a number to continue...&goto:setnum 

:setname 
set /P "name=Enter "root" name of file:" 
If not defined name echo.&Echo You must enter the name of your new files to continue...&goto:setname 

:setext 
set /P "ext=What will be the file extension?:" 
If not defined ext echo.&Echo You must enter an extension to continue...&goto:setext 

pause 
%ext:~0,1% | FINDSTR /R "[.]" && pause & goto:extNoDot 
%ext:~0,1% | FINDSTR /R "[.]" || pause & goto:extYesDot 

:extNoDot 
for /L %%a in (1,1,%num%) do (echo %%a >> !name!%%a%ext%) 
goto:eof 

:extYesdot 
for /L %%a in (1,1,%num%) do (echo %%a >> !name!%%a.%ext%) 
goto:eof 

:eof 
EXIT /b 

回答

1

你實際上沒有說明你當前的代碼有什麼問題。如果沒有測試它,我可以看到,這兩條線必須給你的問題:

%ext:~0,1% | FINDSTR /R "[.]" && pause & goto:extNoDot 
%ext:~0,1% | FINDSTR /R "[.]" || pause & goto:extYesDot 

這是因爲你在一行的開頭有%ext:~0,1%就好像它是一個命令。你似乎試圖做的是將這些傳遞給FINDSTR命令。因此,您需要回顯它們:

echo %ext:~0,1% | FINDSTR /R "[.]" && pause & goto:extNoDot 
echo %ext:~0,1% | FINDSTR /R "[.]" || pause & goto:extYesDot 

但是,在這裏使用外部命令是矯枉過正。你應該做的,而不是執行以下操作:

rem Remove any optional dot at the start 
if "%ext:~0,1%" == "." set "ext=%ext:~1%" 

然後而已矣彷彿ext從來沒有在第一時間點(無需單獨nodotyesdot標籤)。

+0

謝謝!這樣更優雅的解決方案。並感謝澄清兩個findstr線無論如何。我沒有意識到它需要回聲。救了我! – Glycoversi

相關問題