Page 1 of 1

merge files and write the original filename before the content (batch) [resolved]

Posted: 11 Nov 2016 09:16
by zimxavier
Hello,

I have two files :

File1.txt
content1 content1 content1 content1 content1 content1
content1 content1 content1 content1 content1 content1

File2.txt
content2 content2 content2 content2 content2 content2
content2 content2 content2 content2 content2 content2

I need to merge them and have the original filename before the content :

Output.txt
File1.txt
content1 content1 content1 content1 content1 content1
content1 content1 content1 content1 content1 content1
File2.txt
content2 content2 content2 content2 content2 content2
content2 content2 content2 content2 content2 content2

I think there is an easy way to do that in batch language, I don't remember how. Could you help me ?

Thank you !

Re: merge files and write the original filename before the content (batch)

Posted: 11 Nov 2016 09:18
by Squashman
You could do this multiple ways.

Code: Select all

@echo off

(FOR %%G IN ("file1.txt" "file2.txt") DO (
   echo %%~G
   type "%%~G")
)>output.txt

(echo file1.txt
type file1.txt
echo file2.txt
type file2.txt
)>output2.txt

echo file1.txt>output3.txt
type file1.txt>>output3.txt
echo file2.txt>>output3.txt
type file2.txt>>output3.txt

(FOR %%G IN (File*.txt) DO (
   echo %%G
   type "%%~G")
)>Output4.tmp
rename Output4.tmp Output4.txt

Re: merge files and write the original filename before the content (batch)

Posted: 11 Nov 2016 10:10
by zimxavier
Thank you Squashman,

Your fourth example is interesting in my case, because of the token (I have many more files than two and I don't want write their names each time)
All is okay.

Batch used :

@echo off

(FOR %%G IN (text*.txt) DO (
echo %%G
type "%%~G")
)>Output.tmp
rename Output.tmp Output.txt

Re: merge files and write the original filename before the content (batch)

Posted: 11 Nov 2016 10:19
by Squashman
That is because the last line of file 1 does not have a CRLF.

Re: merge files and write the original filename before the content (batch)

Posted: 11 Nov 2016 10:20
by zimxavier
Indeed. I edited my post.

Re: merge files and write the original filename before the content (batch)

Posted: 11 Nov 2016 10:25
by Squashman
So if one of your files does not have a CRLF on the last line you can pipe the output to FINDSTR before the redirect.

Code: Select all

(FOR %%G IN (File*.txt) DO (
   echo %%G
   type "%%~G"|findstr "^")
)>Output4.tmp
move /Y Output4.tmp Output4.txt