需要注意的是:for在单独使用的时候,变更可以为:%a
但放到批处理文件中时,要用 %%a ,否则变更出错。
1. 删除 指定目录下 删除bin,obj两个目录及子目录
for /r %local_filepath%%local_filename%\. %%a in (bin,obj) do @if exist %%a rd /q/s "%%a"
2. 删除 指定目录下 扩展名为:scc,vspscc,vssscc的文件
for /r %local_filepath%%local_filename%\. %%a in (*.scc,*.vspscc,*.vssscc) do @if exist %%a del /q/s/f "%%a"
3.
A.TXT分布在几个文件夹内数量不确定怎么样才可以用批处理直接查找出来替换
A.txt品名 序列号笔 000000A4纸 111111U盘 222222B.txt笔123456A4纸7777U盘78945批处理修改结果A.txt品名 序列号笔 笔123456A4纸 A4纸7777U盘 U盘78945
@echo off&color a&setlocal enabledelayedexpansionset /a n1=-1for /f "tokens=1,2 delims= " %%a in (A.txt) do (set /a n1+=1if %%a equ 品名 (echo %%a %%b>>modified.txt) else (for /f "delims=" %%h in (B.txt) do (set /a n2+=1if !n1! equ !n2! echo %%a %%h>>modified.txt))set /a n2=!n1!)在A.txt和B.txt所在的文件夹下执行,生成的modified.txt就是你想要的结果
4.txt文件,把里面的所有3.6改成6*3
@echo offsetlocal enabledelayedexpansionset file=set /p file= 请输入要操作的文件名称(包括扩展名):set "file=%file:"=%"for %%i in ("%file%") do set file=%%~fiset replaced=set /p replaced= 请输入即将被替换的内容:set all=set /p all= 请输入替换字符串:for /f "delims=" %%i in ('type "%file%"') do ( set str=%%i set "str=!str:%replaced%=%all%!" echo !str!>>"%file%"_tmp.txt)copy "%file%" "%file%"_bak.txt >nul 2>nulmove "%file%"_tmp.txt "%file%"start "" "%file%"
5.查找并替换文本内容
@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%i in (test.txt) do (
set str=%%i
set str=!str:3.6=6.3!
echo !str!>>tmp.txt
pause
)
echo OK
endlocal enabledelayedexpansion
pause
6.DOS批量处理替换~文本字符
例: A.TXT 如下:abcdbbcd要求输出为 B.TXT12344567
@echo offsetlocal enabledelayedexpansionfor /f "delims=" %%i in (a.txt) do (set a=0set str=%%icall :doecho.>>b.txt)pause:docall set sth=%%str:~%a%,1%%for %%a in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do (set /a b+=1if "!sth!" equ "%%a" (set /p=!b!
7.
test.cmd的同级目录下有一个list文件夹, 文件夹里有一个test.txt , test.txt 里面放了文件的路径,如: com/comp/util/a.java com/comp/util/b.java
需要把com/comp/util/a.java 变成本机的一个目录
FOR /R "./list/" %%i IN (*.txt) DO ( echo "********* [check file list : " %%i "] ***********" for /F "tokens=1 delims=" %%j IN (%%i) do ( set file_name=%%~nj%%~xj set file_path=%%~fj set file_path=%%file_path:!file_name!=%% echo at end !file_path! echo at end !file_name! ))
8.
有一个txt文件,想把里面的1.1.1.1 全部替换成 2.2.2.2
@echo offsetlocal enabledelayedexpansionset file=set /p file= 请输入要操作的文件名称(包括扩展名):set "file=%file:"=%"for %%i in ("%file%") do set file=%%~fiecho.set replaced=set /p replaced= 请输入即将被替换的内容:echo.set all=set /p all= 请输入替换字符串:for /f "delims=" %%i in ('type "%file%"') do ( set str=%%i set "str=!str:%replaced%=%all%!" echo !str!>>"%file%"_tmp.txt)copy "%file%" "%file%"_bak.txt >nul 2>nulmove "%file%"_tmp.txt "%file%"start "" "%file%"