Batch File to edit specific lines of Text

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
juannfox
Posts: 2
Joined: 13 Sep 2017 09:21

Batch File to edit specific lines of Text

#1 Post by juannfox » 13 Sep 2017 09:34

Hi guys,
so I've been trying to make the software installation at work more automated and I wonder: Can I make a batch file to edit two specific lines in a text file?
The file consists of this lines:

extension=
posicion=
queue=1800
SITIO=AvayaCM

Next to both "extension=" and "posicion=" I have to manually add a number specific to that X computer. My idea is to make a batch file that prompts the user to enter the number and then automatically edits and saves the file.
For Example, If I enter 3438 in the promt, the file after that would consist of:
extension=3438
posicion=3438
queue=1800
SITIO=AvayaCM


Any clues? I preciate the help!
Cheers

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Batch File to edit specific lines of Text

#2 Post by aGerman » 13 Sep 2017 10:17

You can't add in the middle of the file but you can write the new content to a temporary file and afterwards replace the original file.

Code: Select all

@echo off &setlocal
set "file=test.txt"

set /p "extension=extension="
set /p "posicion=posicion="

setlocal EnableDelayedExpansion
<"!file!" >"!file!.~tmp" (
  for /f %%i in ('type "!file!"^|find /c /v ""') do for /l %%j in (1 1 %%i) do (
    set "line=" &set /p "line="
    if "!line:~,10!"=="extension=" (
      echo(extension=!extension!
    ) else if "!line:~,9!"=="posicion=" (
      echo(posicion=!posicion!
    ) else (
      echo(!line!
    )
  )
)
>nul move /y "!file!.~tmp" "!file!"

Steffen

juannfox
Posts: 2
Joined: 13 Sep 2017 09:21

Re: Batch File to edit specific lines of Text

#3 Post by juannfox » 15 Sep 2017 13:09

aGerman wrote:You can't add in the middle of the file but you can write the new content to a temporary file and afterwards replace the original file.

Code: Select all

@echo off &setlocal
set "file=test.txt"

set /p "extension=extension="
set /p "posicion=posicion="

setlocal EnableDelayedExpansion
<"!file!" >"!file!.~tmp" (
  for /f %%i in ('type "!file!"^|find /c /v ""') do for /l %%j in (1 1 %%i) do (
    set "line=" &set /p "line="
    if "!line:~,10!"=="extension=" (
      echo(extension=!extension!
    ) else if "!line:~,9!"=="posicion=" (
      echo(posicion=!posicion!
    ) else (
      echo(!line!
    )
  )
)
>nul move /y "!file!.~tmp" "!file!"

Steffen


Works like a charm! I really apreciate this man, thanks for taking the time to answer and code that.
Cheers from Argentina

Post Reply