批出理命令学习笔记
-
运行很简单,随便新建一个 filename.txt 文件,然后把后缀 .txt 改为 .cmd , 保存后双击就可以运行了
-
如果需要看到运行结果,需要在文件末尾加上 “pause” 命令
-
@echo off - 简化命令,就是将输入的命令隐藏起来,一般以这个开头
1.定义一个变量并获取命令行输入:
@echo off
set /p input=输入数据
pause
2.输出变量里面的值:
@echo off
echo %input%
pause
3.批处理中的goto语句
@echo off
:jumpTo
echo 1
goto jumpTo
pause
::这个会无限循环输出1
4.批处理中的if语句
@echo off
setlocal enabledelayedexpansion
set x=10
if %x% == 10 (
set test=测试
echo !test!
echo %test%
echo x等于10
)else (
echo x不等于10
)
pause
::if语句段里面需要注意,!变量! (局部变量),%变量% (全局变量)
::同时定义了局部变量需要开启变量延迟扩展 setlocal enabledelayedexpansion
5.批出理中的for循环
@echo off
::输出1到10 FOR /L %variable IN (start,step,end) DO command [command-parameters]
for /L %%i in (1,1,10) do (
echo %%i
)
pause
6.批出理中的函数
@echo off
:func
::这就相当于创建了一个名为func的函数
echo 函数名 - func
pause>nul
EXIT /B 0
::用call去调用函数
call :func
7.案例:案例具有的功能 -> 具有查看、修改、删除、查找等功能
@echo off
setlocal enabledelayedexpansion
echo 提示:如果需要查看当前目录下所有文件,可以直接输入“dir”,删除文件可以输入“del”
echo.
:name
set /p fileName=请输入需要操作文件的文件名:
if %fileName% == dir (
dir
echo.
goto name
)
if %fileName% == del (
echo.
echo 提示:输入all删除当前目录下的文件,输入ALL删除所有文本文件不需要确认
set /p input=请输入需要删除的文件名,不需要加文件名后缀:
if !input! == all (
del /p /s *.txt
echo.
goto name
)
if !input! == ALL (
del /s *.txt
echo.
goto name
)
del .\!input!.txt
echo.
echo 已删除文件"!input!.txt".....
echo.
goto name
)
::获取输入字符串的长度
set /a num=0
set str=%fileName%
set "str=%str:"= %"
:next
if not "%str%"=="" (
set /a num+=1
set "str=%str:~1%"
goto next
)
if %num% GTR 3 (
set str=%fileName:~-3%
)else (
set str=%fileName%
)
::判断是否加了文件名后缀,如果没有自动加上
if %str% == txt (
call :testFunction
)else (
set fileName=%fileName%.txt
call :testFunction
)
::实现各操作指令函数
:testFunction
echo.
echo 正在操作文件"%fileName%".......
:test
echo.
echo 操作指令:退出/out 、查找/find 、 添加数据/add 、 查看文件/view 、目录/dir
set /p input=请输入需要操作的指令:
if %input% == out (
exit
)else (
if %input% == view (
echo.
type .\%fileName%
echo.
goto test
)
if %input% == find (
:find
set /p content=请输入需要查找的内容("N"退出查找):
find /n "!content!" ./%fileName%
echo.
if !content! == N (
echo.
echo 已退出find命令......
echo.
goto test
)
goto find
)
if %input% == add (
echo 请输入需要添加的数据("N"退出输入,"clear"清空,回车换行):
:save
set /p input=:
for %%a in (%fileName%) do (
if !input! == N (
echo.
echo 数据添加成功.......
goto test
)
if !input! == clear (
echo.
type nul > .\%%a
echo 文件中的内容已清空.......
goto test
)
echo !input! >> .\%%a
)
goto save
)
if %input% == dir (
dir
echo.
goto name
)
echo.
echo 输入有误,请重新输入......
goto test
)
EXIT /B 0
pause>nul