|
Answer» Hi guys,
Im trying to add a line of code into a .txt file using a batch file, but want to add it ad a certain point.
The .txt file is called 'test.txt' and located on my DESKTOP and the contents of the .txt file are -
this is line 1 this is line 2 this is line 3
My code as present is -
@ECHO OFF start notepad "C:\Users\xxx\Desktop\test.txt" echo. >>"C:\Users\xxx\Desktop\test.txt" echo ADDED text>>"C:\Users\xxx\Desktop\test.txt" TASKKILL /F /IM notepad.exe
This batch file opens the file and changes it to -
this is line 1 this is line 2 this is line 3
added text
And then closes it.
I want to put the "added text" after "this is line 2" so it shows -
this is line 1 this is line 2 added text this is line 3
Can anybody help me please?Notepad is not scriptable using batch language. You could use VBScript or Powershell which WOULD make quick work of this TASK. In batch you need to script the file contents. This little snippet is specific to your situation, but it works:
Code: [Select]@echo off setlocal enabledelayedexpansion
for /f "delims=" %%i in (C:\Users\xxx\Desktop\test.txt) do ( set /a COUNT=!count!+1 if !count! GEQ 3 goto next echo %%i >> C:\Users\xxx\Desktop\test.new )
:next echo This is Added Text >> C:\Users\xxx\Desktop\test.new for /f "skip=2 delims=" %%i in (C:\Users\xxx\Desktop\test.txt) do ( echo %%i >> C:\Users\xxx\Desktop\test.new )
Your Win7 machine comes installed with better tools than batch (Powershell and VBScript among them). Have you considered using any of them?
Good luck. Make sure you always initialize your variables. You could just simplify this a bit as well.
Code: [Select]@echo off setlocal enabledelayedexpansion
set count=0 for /f "delims=" %%i in (C:\Users\xxx\Desktop\test.txt) do ( set /a count=!count!+1 if !count! NEQ 3 ( echo %%i >> C:\Users\xxx\Desktop\test.new ) else ( echo ADDED TEXT HERE >> C:\Users\xxx\Desktop\test.new ) )
|