涉及知識點:
1、如何定義一個函數
2、如何傳遞參數
3、如何調用?
4、如何獲取返回值
5、GOTO:EOF 和 exit /b 0的區別
6、如何在字符串替換的時候處理變量
7、具體實例
正文部分:
1、定義
:functionname rem 參數是 %0,%1,...%n rem todo goto:eof
2、參數和調用
call :functionname 參數1(對應%1),參數2(對應%2),...參數n(對應%n)
4、關於返回值,直接修改全局變量,批處理是沒有函數返回值的
5、關於goto:eof和exit /b 0的區別
rem goto:eof 相當於函數的} 結尾標記,返回到調用者位置 rem exit /b 0 結束當前cmd,返回exitCode 0
6、字符串替換中處理變量
1 set str_find=%1 2 set str_replace=%2 3 set str_string=%3 4 5 ::call命令會對其參數進行擴展 6 ::call set "strok=%%str_string:!str_find!=!str_replace!%%" 7 8 ::也可以啟用變量延遲來實現 9 ::@echo off&setlocal enabledelayedexpansion 10 ::set "var=!var:%mat%=! 11 12 set "strok=!str_string:%1=%2!"
7、具體實例
@echo off SETLOCAL ENABLEDELAYEDEXPANSION title bat function ::author:lovelp ::link:http://www.cnblogs.com/lovelp/p/5720046.html set str1="this is a old string" set str2="this is a new string" echo= ::============================================= ::設置變量strok,全局,用於實現函數返回值 set strok=" " echo 函數調用語句為: call :func1 this is a old string,this is a new string echo 函數結束參數,分別為 %%0,%%1,%%2,...,%%n call :func1 %str1%,%str2% echo 以上結果是解釋函數參數 echo. echo 下面才是重點,調用自定義函數實現字符串替換 echo. echo call :fun_replace old,舊的,this is a old string call :fun_replace old,舊的,%str1% echo. echo ↓↓↓↓調用結束,顯示結果↓↓↓↓↓↓↓ echo %strok% ::============================================= exit /b 0 :fun_replace set str_find=%1 set str_replace=%2 set str_string=%3 echo 查找的字符串是: !str_find! echo 最終替換后的字符串是: !str_replace! echo 字符串主體是: %str_string% ::call命令會對其參數進行擴展 ::call set "strok=%%str_string:!str_find!=!str_replace!%%" ::也可以啟用變量延遲來實現@echo off&setlocal enabledelayedexpansion ::set "var=!var:%mat%=! set "strok=!str_string:%1=%2!" GOTO:EOF ::exit /b 0 REM (1) 運行 GOTO :EOF 后, CMD 返回並將等待下一條命令. REM (2) 運行 EXIT 后, CMD 將直接關閉並返回到曾啟動 cmd.exe 的程序或返回到”資源管理器”. REM (3) 運行 EXIT /B 后, CMD 將直接關閉並返回到曾啟動 cmd.exe 的程序或返回到”資源管理器”. ::函數名 :func1 帶冒號哦 ::參數1,%0 就是函數名本身 :func1 ::函數2、3...n 就是常見的形參了 :func1 echo %%0 is %0 echo %%1 is %1 echo %%2 is %2 GOTO:EOF pause