2014-08-31 82 views
0

我希望批處理文件搜索?符號並將其替換爲txt文件中的%符號要搜索的批處理文件?並在txt文件中用%替換它

我看到很多搜索和替換代碼,它不會被替換嗎?與%

如果任何一個有代碼,它工作在VBS張貼

例如:

@echo off  
setlocal 
set "search=?"        
set "replace=%"        
set "textfile=test.txt" 
set "newfile=newtest.txt" 

(for /f "delims=" %%i in ('findstr /n "^" "%textfile%"') do (
set "line=%%i" 
setlocal enabledelayedexpansion 
set "line=!line:%search%=%replace%!" 
echo(!line! 
endlocal 
))>"%newfile%" 
type "%newfile%" > nul 
+0

@Mofi - 只是發佈這個答案。儘管我不確定OP是否想要新文件中的行號 – npocmaka 2014-08-31 21:21:49

+0

thankyou mofi它是工作! – user3752270 2014-08-31 21:28:05

回答

1

此批解決方案比有問題的批處理腳本更好,因爲它不添加行號到新的文件。

@echo off 
setlocal EnableDelayedExpansion 
set "search=?" 
set "replace=%%" 
set "textfile=test.txt" 
set "newfile=newtest.txt" 
if exist "%newfile%" del "%newfile%" 
for /F "usebackq delims=" %%L in ("%textfile%") do (
    set "Line=%%L" 
    set "Line=!Line:%search%=%replace%!" 
    if not "!Line: =!"=="" echo !Line!>>"%newfile%" 
) 
endlocal 

注意!

空白行,並與test.txt僅僅空格線的複製與?%取代線newtest.txt刪除。只有水平製表符的行會導致寫入新文件的狀態爲echo。所以我建議使用文本編輯器進行替換,而不是使用批處理文件進行替換,儘管我認爲可以改進代碼以僅將空白行和空行復制到新文件中。

0

這可以使用PowerShell的幫助可以輕鬆實現,使用一個命令行的,正確的從命令控制檯。請參閱下面的示例。如果您打算在批處理文件中使用它,請將%替換爲%%。

C:\Scripts>type input.txt 
Sometext ? here 
here is another ? text 
?? test file.. 
sample?? 

C:\Scripts>powershell -command (get-content input.txt ^| %{ $_ -replace \"\?\",\"%\"}) 
Sometext % here 
here is another % text 
%% test file.. 
sample%% 

乾杯,G

+0

必須對其進行修改才能使其在批處理文件中工作 - '%'需要加倍到'%%' – foxidrive 2014-09-01 04:29:07