romeo 8812
romeo 8812

Reputation: 75

Insert new lines after the last line of a paragraph in a file using batch file

I want to insert a line to the end of paragraph in file using a batch script. In my file the line last of paragraph is not clear. It is variable which has form "LoadModule name moduleName ".

new line: "LoadModule new_module module/mod_newmod.so"

my file input.conf

abc def xyz 

LoadModule foo_module libexec/mod_fooa.so
LoadModule proxy_module libexec/mod_proxy.so
LoadModule lmn_module libexec/mod_abc.so
LoadModule xyz_module libexec/mod_def.so

ExtendedStatus controls whether Apache will generate "full" status

and result:

abc def xyz 

LoadModule foo_module libexec/mod_fooa.so
LoadModule proxy_module libexec/mod_proxy.so
LoadModule lmn_module libexec/mod_abc.so
LoadModule xyz_module libexec/mod_def.so
LoadModule new_module module/mod_newmod.so

ExtendedStatus controls whether Apache will generate "full" status

A new line "LoadModule new_module module/mod_newmod.so" get inserted at last of LoadModule paragraph. Please suggest a solution for this. Thank so much.

Upvotes: 2

Views: 269

Answers (1)

dbenham
dbenham

Reputation: 130819

@echo off
setlocal
set "file=test.txt"
set "here="
for /f "delims=:" %%A in ('findstr /lnbc:"LoadModule" "%file%" 2^>nul') do set here=%%A
if defined here (
  >"%file%.new" (
    for /f "tokens=1* delims=:" %%A in ('findstr /n "^" "%file%"') do (
      echo(%%B
      if %%A==%here% echo(LoadModule new_module module/mod_newmod.so
    )
  )
  move /y "%file%.new" "%file%"
)
type "%file%"

This solution assumes that none of your existing lines begin with :. A different solution is required if any lines do begin with :.

EDIT - Updated answer to do nothing if test.txt does not exist or if test.txt does not contain any existing line starting with "LoadModule".

Upvotes: 2

Related Questions