I have a text file which has more than 200 lines in it, and I just want to add a new line before line 4. I'm using Windows XP.
Example text file before input:
header 1
header 2
header 3
details 1
details 2
After output:
header 1
header 2
header 3
<----- This is new line ---->
details 1
details 2
I believe you are using the
echo Text >> Example.txt
function?
If so the answer would be simply adding a "." (Dot) directly after the echo with nothing else there.
Example:
echo Blah
echo Blah 2
echo. #New line is added
echo Next Blah
You can use:
type text1.txt >> combine.txt
echo >> combine.txt
type text2.txt >> combine.txt
or something like this:
echo blah >> combine.txt
echo blah2 >> combine.txt
echo >> combine.txt
echo other >> combine.txt
DISCLAIMER: The below solution does not preserve trailing tabs.
If you know the exact number of lines in the text file, try the following method:
@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /P L=
IF %%i==%insertbefore% ECHO(
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.
After finishing, the original file is deleted and the temporary one gets assigned the original name.
UPDATE
If the number of lines is unknown beforehand, you can use the following method to obtain it:
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
(This line simply replaces the SET totallines=200
line in the above script.)
The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.
Suppose you want to insert a particular line of text (not an empty line):
@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1
@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /p L=
IF %%i==%insertat% ECHO(!TL!
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%