2012-05-12 71 views
0

我在具有「}」分隔符的不同子目錄下有許多同名文件。我想查找一組特定的文本並在分隔符之前附加一些新的文本。例如:使用批處理或vbs查找和替換/附加文件中的文本

folder1\sample.css 
    .asd {} 
    .bar {} 
folder2\sample.css 
    .foo {} 
    .bar {} 

所有sample.txt的文件應該再像:

.. 
.foo {display:none;} 
.. 

我將如何做到這一點使用VBS,PowerShell的,最好一個批處理文件? 事情類似:

SETLOCAL ENABLEDELAYEDEXPANSION 
for /r %%f in (*.txt) do (
    for /f "delims=}" %%a in (%%f) do (
     set str=%%a 
     REM modify the variable 
     REM replace the line with the variable 
    ) 
) 

編輯: 我懂了工作,但我敢肯定,這可能是更多的可重用性更好的編寫。

@echo off 
SETLOCAL ENABLEDELAYEDEXPANSION 
for /r %%f in (index.css) do (
    BatchSubstitute.bat ".foo {" ".foo { display:none;" %%f>%%f.new 
    del %%f 
    BatchSubstitute.bat ".bar {" ".bar { display:none;" %%f.new>%%f 
    del %%f.new 
    BatchSubstitute.bat ".asd {" ".asd { display:none;" %%f>%%f.new 
    del %%f 
    ren %%f.new index.css 
) 

BatchSubstitute.bat

@echo off 
REM -- Prepare the Command Processor -- 
SETLOCAL ENABLEEXTENSIONS 
SETLOCAL DISABLEDELAYEDEXPANSION 

::BatchSubstitude - parses a File line by line and replaces a substring" 
::syntax: BatchSubstitude.bat OldStr NewStr File 
::   OldStr [in] - string to be replaced 
::   NewStr [in] - string to replace with 
::   File [in] - file to be parsed 
:$changed 20100115 
:$source http://www.dostips.com 
if "%~1"=="" findstr "^::" "%~f0"&GOTO:EOF 
for /f "tokens=1,* delims=]" %%A in ('"type %3|find /n /v """') do (
    set "line=%%B" 
    if defined line (
     call set "line=echo.%%line:%~1=%~2%%" 
     for /f "delims=" %%X in ('"echo."%%line%%""') do %%~X 
    ) ELSE echo. 
) 
+0

CMD對此不太合適。我建議你使用你更熟悉的VBS和Powershell。 – Ben

回答

1

你可以利用這個批處理文件:http://www.dostips.com/?t=Batch.FindAndReplace

請對你在你尋求查找文件的循環中調用/的.foo {}.foo{display:none;}取代。

可能比使用這個查找/替換批次更好的查找/替換二進制文件,但它可能會完成這項工作。

相關問題