3

I am completely new to Batch files and have been tinkering around with simple commands. I have figured out how to move text to another file, find a line etc., but I want to be able to add a few lines of text into an already existing text file. Here is what I have so far:

@ECHO OFF
CD C:\Documents and Settings\SLZ1FH\Desktop\New Folder
FOR /F "tokens=*" %%A IN (Examples.txt) DO (
  ECHO %%A
  IF %%A=="Ex3 3"(
    TYPE Line_to_add.txt >> Examples.txt
  )
)

if Examples.txt contains:

  • Ex1 1
  • Ex2 2
  • Ex3 3
  • Ex4 4
  • Ex5 5

and Line_to_add.txt contains:

  • This is a line
  • This is another line just for kicks!

I would like the output to be:

  • Ex1 1
  • Ex2 2
  • Ex3 3
  • This is a line
  • This is another line just for kicks!
  • Ex4 4
  • Ex5 5

tia :)

Solution

@ECHO OFF
FOR /F "tokens=*" %%A IN (Examples.txt) DO (
  ECHO %%A
  IF "%%A" EQU "Ex3" (
    TYPE Line_to_add.txt
  )
) >> temp.txt
move /y temp.txt Examples.txt
Stoating
  • 411
  • 3
  • 6
  • 12

3 Answers3

6

You never bothered to ask a question, but I can see a few problems with your code.

1) Your IF statement is broken because the left paren is treated as part of the string to be compared. You must have at least one space before your paren.

2) Your comparison will never find a match because the quotes are included in the comparison. Your values have spaces, so both sides of the comparison should be enclosed in quotes.

3) You are attempting to insert into the existing file, which cannot work. Your code would simply append the text to the end of the file. You must write the entire desired result to a new temp file, and then move the temp file to the original name.

First I will ignore the update of the file and show how to get the correct output to the screen.

@ECHO OFF
FOR /F "tokens=*" %%A IN (Examples.txt) DO (
  ECHO %%A
  IF "%%A" EQU "Ex3 3" (
    TYPE Line_to_add.txt
  )
)

It is then simple to direct the output to a file and move the file to the desired name.

@ECHO OFF
(
  FOR /F "tokens=*" %%A IN (Examples.txt) DO (
    ECHO %%A
    IF "%%A" EQU "Ex3 3" (
      TYPE Line_to_add.txt
    )
  )
) >temp.txt
move /y temp.txt Examples.txt

Good resources for learning batch syntax and techniques:

1) Every command has online help. Simply add the /? option after the command name. For example, DIR /?

2) Here are some sites with good info

http://www.dostips.com/
http://judago.webs.com/
http://www.robvanderwoude.com/batchfiles.php

dbenham
  • 127,446
  • 28
  • 251
  • 390
  • Thank you very much for this. The code works perfect. What source would you recommend I read to learn the syntax and rules of writing .bat files? – Stoating May 07 '12 at 16:59
  • @ZacharySlade - I've added some reference material to my answer. If you get an answer that works for you, please check the answer as correct. This removes your question from the "Unanswered questions" list, and also awards 15 points to the person that answered your question, as well as 2 points to yourself. – dbenham May 07 '12 at 17:40
  • I know it's an old post but I want to know how do you do it if you have numerous file(examples.txt) and you will only insert the Line_to_add.txt after a specific line? – lovelyvm Feb 01 '16 at 03:15
  • Very helpful, any idea how to allow it to maintain whitespace at the beginining of each line? Ex: trying to inject a couple lines of code into some C# files. Losing my indents. – Adam Plocher Jun 22 '18 at 02:00
  • @AdamPlocher Change `"tokens=*"` (all tokens, but leading default delimiter chars of tab and space are stripped) to `"delims="` (no delimiter so always a single token, nothing stripped) – dbenham Jun 22 '18 at 03:17
  • @dbenham thanks for the quick response. That's not working, I'm now getting an empty "temp.txt" file. I have your second example exactly (minus the last "move" call, and with a different input text file). Replaced the "*" with nothing, so `FOR /F "tokens=" %%A...`, get a zero byte text file outputted now (before was getting text, just with whitespace stripped from each line)... – Adam Plocher Jun 22 '18 at 04:51
  • Oh I'm a dummy, didn't notice you changed the keyword to delims instead of tokens.. Sorry, trying now and will report back in a sec. EDIT: just tried it, worked perfectly. Thank you! – Adam Plocher Jun 22 '18 at 05:00
  • Sorry to keep bugging you but one more problem now that I'm experiencing: blank lines are stripped completely. This is a code file so I have double spacing between method names (for example) and those are all removed. Any way to keep those intact? :) If not, no biggy, just curious. Should prob use powershell instead, but there's something fun about trying to make a bat file do what you want... since almost everything you want is accomplished by a hack and something it was never designed to do. lol – Adam Plocher Jun 22 '18 at 05:09
  • https://stackoverflow.com/questions/38723595/preserve-empty-lines-in-a-text-file-while-using-batch-for-f – Adam Plocher Jun 22 '18 at 05:13
  • Last comment (I swear), I just noticed you were the guy on the other link I pasted too, and the author of this JRepl file I'm looking at now. This things a beast, thank you! – Adam Plocher Jun 22 '18 at 05:21
0

Use FOR /F to iterate the lines in the file, use SET /a to create a counter.

For each line in the file, CALL a subroutine which increaments the counter and test it. If it has some value, insert your new data as you have done so far.

Here is your script, updated. You can use a counter or the contents of the file to trigger an insert. It also handles the case where the input and output files have the same name.

@ECHO OFF
set INFILE=Examples.txt
set OUTFILE=Output.txt
set MIXFILE=Line_to_add.txt

set OUTFILEOLD=%OUTFILE%
if NOT "%INFILE%"=="%OUTFILE%" got no_tmp1
set OUTFILE=%OUTFILE%.tmp
:no_tmp1

set counter=0
FOR /F "tokens=*" %%A IN (%INFILE%) do call :process_line %%A

set OUTFILE=%OUTFILEOLD%
if NOT "%INFILE%"=="%OUTFILE%" goto no_tmp2
copy %OUTFILETMP% %OUTFILE%    
:no_tmp2

goto exit

:process_line
set /a counter=counter+1
echo Line %counter% = %*
REM ##IF "%counter%"=="3" goto :adding_line 
IF /i "%1"=="Ex3" goto :adding_line
echo %* >> %OUTFILE%
goto :EOF

:adding_line
echo Adding line
type %MIXFILE% >> %OUTFILE%
goto :EOF

:exit
echo DONE
Jay M
  • 3,736
  • 1
  • 24
  • 33
  • literally just copied and pasted my comment from the answer above...:) ... Very helpful, any idea how to allow it to maintain whitespace at the beginining of each line? Ex: trying to inject a couple lines of code into some C# files. Losing my indents. – Adam Plocher Jun 22 '18 at 02:01
0
1) create new temp file
2) output to temp
3) delete original
4) rename temp to original

Can't think of anything better.

Agent_L
  • 4,960
  • 28
  • 30
  • Thank you for your post, but it seems to me the problem is the following: IF %%A=="Ex3 3". What would be the correct comparison there? – Stoating May 07 '12 at 16:18
  • @ZacharySlade IF "%%A"=="Ex3 3". Your question gave an impression that the code is working, but gives wrong results : ) – Agent_L May 07 '12 at 16:26
  • I'd rather not delete the original file to preserve metadata like original date of creation and modification. Isn't there a solution that doesn't require a temp file to be made? – Prid Aug 18 '21 at 22:26