简体   繁体   中英

Replace string in a file using batch script. I have the below code but it's adding blank space at the end of each line

Replace string in a file using batch script. I have the below code but it's adding blank space at the end of each line. It is affecting the job process while loading. Is there any easy way to replace like replace in notepad?

@ECHO OFF
setlocal enabledelayedexpansion
set "search=%Old text"
set "replace=%new text"
set txtfile=D:\new_%date:~-7,2%%date:~-10,2%%date:~-4,4%.txt
set newfile=D:\new_D%date:~-7,2%%date:~-10,2%%date:~-4,4%_T%time:~-11,2%%time:~-8,2%%time:~-5,2%.txt
if exist "%newfile%" del /f /q "%newfile%"
for /f "tokens=*" %%a in (%txtfile%) do (
set newline=%%a
set newline=!newline:%search%=%replace%!
echo !newline! >> %newfile%

)
copy %newfile% %textfile%

try to replace this :

echo !newline! >> %newfile%

by this :

>>%newfile% echo !newline!

EDIT : You'll better use (echo !newline!) like proposed by @MC ND

EDIT II : If you want something quicker (for big file) use a BAT/Powershell

@echo off
setlocal
set $source=%cd%\out.txt
set $Dest=%cd%\out1.txt

set "search=Old"
set "replace=New"

for /f "delims=" %%a in ('powershell -c "(get-content '%$source%') | foreach-object {$_ -replace '%Search%', '%replace%'} | set-content '%$dest%'"') do echo %%a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM