1

I am doing some modifications on a text file; however the program is adding lines instead of modifying them.

As i am new to it, can you help or guide me?

Here is my code:

setlocal enabledelayedexpansion 
for /f "delims=" %%a in (economic_changes.txt) do ( 
   SET s='%%a 
   SET s=!s:;= ! 
   SET s=!s:- =-;;! 
   SET s=!s: -=-! 
   SET s=!s:-;;-=-;-! 
   SET s=!s:-=%!
   SET s=!s:_= %!
   SET s=!s:;=';'%!
   SET s=!s:;'';'=;;%!

   echo !s! 
) >>  "%userprofile%\desktop\Economic_Folder\economic_changes.txt"
Compo
  • 30,301
  • 4
  • 20
  • 32
  • [\[MSDN\]: Using command redirection operators](https://technet.microsoft.com/en-us/library/bb490982.aspx): "_**>>** - Appends the command output to the end of a file without deleting the information that is already in the file._", so that is the expected behavior. One way of achieving your goal would be to output every line (whether it's modified or not) in a different file (empty at the beginning), and at the end move it over the original one. – CristiFati Jun 08 '17 at 17:08

2 Answers2

0

Since the same file cannot be read and written at the same time, create a temporary file to store the changed lines into.

Several of the modifications have a SPACE character at the end. Using quotes makes it clear where those occur. Perhaps you want those. I do not know.

Then, of course, delete the temporary file once completed.

setlocal enabledelayedexpansion

SET "TMPFILE=%TEMP%\file_converter_%RANDOM%.tmp"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")

for /f "delims=" %%a in (economic_changes.txt) do (
   SET "s='%%a "
   SET "s=!s:;= ! "
   SET "s=!s:- =-;;! "
   SET "s=!s: -=-! "
   SET "s=!s:-;;-=-;-! "
   SET "s=!s:-=%!"
   SET "s=!s:_= %!"
   SET "s=!s:;=';'%!"
   SET "s=!s:;'';'=;;%!"

   echo>>"%TMPFILE% !s!
)

COPY /Y "%TMPFILE%" "%USERPROFILE%\Desktop\Economic_Folder\economic_changes.txt"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")
lit
  • 10,936
  • 7
  • 49
  • 80
0

Here's a "dirty" trick:

@echo off
setlocal enabledelayedexpansion 

set _FILE="%userprofile%\desktop\Economic_Folder\economic_changes.txt"
for /f %%a in ('type %_FILE% ^&^& echo.^>NUL 2^>%_FILE%') do (
    SET s='%%a 
    SET s=!s:;= ! 
    SET s=!s:- =-;;! 
    SET s=!s: -=-! 
    SET s=!s:-;;-=-;-! 
    SET s=!s:-=%!
    SET s=!s:_= %!
    SET s=!s:;=';'%!
    SET s=!s:;'';'=;;%!

    echo !s! 
) >> %_FILE%

The "algorithm":

CristiFati
  • 28,721
  • 9
  • 41
  • 63