append lines of two files without a new line?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Message
Author
Acy Forsythe
Posts: 126
Joined: 10 Jun 2011 10:30

Re: append lines of two files without a new line?

#16 Post by Acy Forsythe » 24 Jun 2011 07:52

Orange_Batch... No offense meant at all, I did not test your script, So you're right I happened to jump in right after Allal posted that, and I took the most recent code to test.

I didn't even pay attention to his changes to your script all I did was post that his changes to your script did work relevant or not it did actually work. I really don't understand the usebackq so I'll have to read up on it. It seems to be a point of contention here.

The only part I changed in your script (aside from using allal's changes)was adding Ltrim and Rtrim at the end which I don't think made anything worse it was a necessary improvement for what I'm doing. The concatenation would leave a trailing space if file1 had more lines and a leading space if file2 had more lines, and I made it a function which was also relevant to what I'm doing but thought I would share my changes.

orange_batch
Expert
Posts: 442
Joined: 01 Aug 2010 17:13
Location: Canadian Pacific
Contact:

Re: append lines of two files without a new line?

#17 Post by orange_batch » 24 Jun 2011 08:02

No worries I took no offense. I noticed your str part, it's a decent addition but there's a better way to do it. Also, usebackq is actually pretty simple, so reading what I wrote under the link I posted is basically all there is to know about it.

Modifying my own code, that "better way" is checking if both the current array1 and array2 variables exist. If so, define the separator. If not, just leave the separator undefined (default) - so only the array that's defined will be echoed anyway.

Code: Select all

@echo off

call :combine "your file1.txt" "your file2.txt" "your outfile.txt" "---"
pause
exit

:: Combine each line of two files.
:combine file1 file2 outfile optional_separator
setlocal
for /f "usebackq tokens=* eol=" %%x in ("%~1") do set /a f_counter1+=1&call set "f_array1-%%f_counter1%%=%%x"
for /f "usebackq tokens=* eol=" %%x in ("%~2") do set /a f_counter2+=1&call set "f_array2-%%f_counter2%%=%%x"
if %f_counter1% LSS %f_counter2% set f_counter1=%f_counter2%
for /l %%x in (1,1,%f_counter1%) do (
if defined f_array1-%%x if defined f_array2-%%x (set "f_separator=%~4")
call echo:%%f_array1-%%x%%%%f_separator%%%%f_array2-%%x%%>>"%~3"
set f_separator=
)
endlocal&exit/b

Ooone more little trick, you can blank the outfile beforehand (like repeated testing) by putting anywhere before the FOR /L within the function: type nul>"%~3"

Post Reply