批處理 去掉字串前後空格
今天找bat處理字串的資料,看到這去掉字串前後空格,覺得很有用。收藏下來,以便以後查閱。
@echo off
:: 去掉左空格
:: Code by JM 2006-11-28 [email protected]
:: 出處:http://www.cn-dos.net/forum/viewthread.php?tid=25172
set "str= ab c&>! "
for /f "tokens=*" %%i in ("%str%") do echo "☆%%i☆"
pause
goto :eof
@echo off
:: 去掉左空格
:: Code by JM 2006-11-28
:: 出處:http://www.cn-dos.net/forum/viewthread.php?tid=25172
set "str= ab c&>! "
:intercept
if "%str:~0,1%"==" " set "str=%str:~1%"&goto intercept
echo "☆%str%☆"
pause
goto :eof
@echo off
:: 去掉右空格
:: Code by JM 2006-11-28
:: 出處:http://www.cn-dos.net/forum/viewthread.php?tid=25172
set "str= ab c&>! "
:intercept
if "%str:~-1%"==" " set "str=%str:~0,-1%"&goto intercept
echo "☆%str%☆"
pause
goto :eof
@echo off
:: 去掉首尾空格空格
:: Code by JM 2006-11-28
:: 出處:http://www.cn-dos.net/forum/viewthread.php?tid=25172
set "str= ab c&>! "
:intercept_left
if "%str:~0,1%"==" " set "str=%str:~1%"&goto intercept_left
:intercept_right
if "%str:~-1%"==" " set "str=%str:~0,-1%"&goto intercept_right
echo "☆%str%☆"
pause
goto :eof
@echo off
:: 去掉所有空格空格
:: Code by JM 2006-11-28 [email protected]
:: 出處:http://www.cn-dos.net/forum/viewthread.php?tid=25172
set "str= ab c&>! "
set "str=%str: =%"
echo "☆%str%☆"
pause
goto :eof
@echo %dbg% off
cls && echo. && echo.
:Redtek 2006 去左、右含有空格的變數試驗與另類方法實現演示
:: 為演示與另做它用方便,所以“標籤程式碼段”內的程式碼都可以獨立使用
:: 出處:http://www.cn-dos.net/forum/viewthread.php?tid=25172
set "var= My name is Redtek "
rem 注:下面 Call 中的引數是無引號的,利用引數以逗號空格等做為分隔的特性
call :去左側空格 %var%
echo. && echo.
call :去右側空格 "%var%"
rem 去字串中的左、右空格
rem 為演示與另做它用的方便,下面步驟將重新編寫去左右空格的程式碼段,可以獨立使用。
echo. && echo.
call :去兩邊空格 "%var%" %var%
goto :eof
:去左側空格
rem 利用替換原理,將變數 var 中 以 ^%1變數內容開頭字串的左邊一切替換為^1本身
rem 因為被 Call 過來以後,引數中的空格就全“丟了”(利用引數分隔的特性),
rem 所以,自然那個要被定位的 ^%1 左邊的空格也就全沒了。
call set "去左空格後的變數=%%var:*%1=%1%%
echo 原字串: [%var%]
echo 去左側空格後的字串: [%去左空格後的變數%]
goto :eof
:去右側空格
rem 將結果賦值給變數,這個變數可以隨便呼叫。
rem ~nx 是利用了“將變數擴充套件到一個檔名”的特性,
rem 既然是合法的檔名,當然檔名後面的空格是無效且無用的~:)
set 去右空格後的變數=%~nx1
echo 原字串: [%var%]
echo 去右側空格後的字串: [%去右空格後的變數%]
goto :eof
:去兩邊空格
rem 原理:先去左邊空格,再去右邊空格,相當於上面演示程式碼的合用:)
rem 在假如沒有上面兩段去左和去右空格的程式碼情況下,下面獨立演示:
set 去左右空格後的變數=%~nx1
call set "去左右空格後的變數=%%去左右空格後的變數:*%2=%2%%"
echo 原字串: [%var%]
echo 去左右空格後的字串: [%去左右空格後的變數%]
goto :eof