标题: [文本处理] 批处理怎样搜索文件并替换文件内容? [打印本页]
作者: wljboy 时间: 2012-5-15 11:17 标题: 批处理怎样搜索文件并替换文件内容?
我刚学习批处理,想请教一个问题:
在d:\soft文件夹下有很多的子文件夹,doc.txt放在其中一个子文件夹下。
我要在d:\soft下搜索这个doc.txt文件,并将doc.txt内的字符orc替换成hum
请问如何实现?
作者: wljboy 时间: 2012-5-15 11:21
- @echo off
- setlocal enabledelayedexpansion
- set var=orc
- for /f "tokens=*" %%j in (doc.txt) do (
- set str=%%j
- echo !str:%var%=hum! >>a.txt)
- del doc.txt
- ren a.txt doc.txt
复制代码
上面这段代码好像只能找到这个bat所在文件夹下的doc.txt,不能找到各个子文件夹的doc.txt
作者: apang 时间: 2012-5-15 12:50
- @echo off
- for /f "delims=" %%i in ('dir /a-d /b /s "d:\soft\doc.txt"') do (
- (for /f "usebackq delims=" %%j in ("%%i") do (
- set "str=%%j"
- setlocal enabledelayedexpansion
- echo !str:orc=hum!
- endlocal
- ))>$
- move $ "%%i"
- )
复制代码
作者: wljboy 时间: 2012-5-15 13:23
非常非常感谢apang
作者: Hello123World 时间: 2012-8-9 18:50
- @echo off
- for /f "delims=" %%i in ('dir /a-d /b /s "d:\soft\doc.txt"') do (
- sed -i 's/orc/hum/g' "%%i"
- >nul ping 127.1
- start "" "%%i"
- )
复制代码
作者: poter 时间: 2012-8-9 19:07
遍历其实很方便的- @echo off
- setlocal enableDelayedExpansion
- for /r %%i in (*) do (
- if "%%~nxi"=="doc.txt" (
- for /f "tokens=*" %%j in (%%i) do (
- set str=%%j&set str=!str:orc=hum!
- echo !str!>>$
- move /y $ %%i
- )
- )
- )
复制代码
作者: poter 时间: 2012-8-9 19:50
vbs- option explicit
- dim a, b, c, d, e, f, g, h, i
- set a = createobject("scripting.filesystemobject")
- set b = a.getfolder("d:\soft")
- for each c in b.subfolders
- set d = a.getfolder(c)
- for each e in d.files
- if right(e, 7) = "doc.txt" then
- sub1 e
- end if
- next
- next
-
- sub sub1(str)
- set f = a.opentextfile(str)
- set g = new regexp
- g.global = true
- g.pattern = "orc"
- i = g.replace(f.readall, "hum")
- a.deletefile str, true
- a.createtextfile(str).write i
- end sub
复制代码
欢迎光临 批处理之家 (http://www.bathome.net/) |
Powered by Discuz! 7.2 |