批处理集锦——(2)自定义函数

涉及知识点:

  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

 

posted @ 2016-07-30 01:00  不要呵呵  阅读(10587)  评论(0编辑  收藏  举报