Search code examples
batch-filemergefilenames

How to write the name of the text file into the text file using bat?


I have a problem. I have many text file (.txt). I want to write the name of the corresponding text files inside them and finally merge them. I have lots of them. I cant do it manually, its too time consuming.

Suppose, i have a text file named "windows.txt" and its contents are

Windows XP
Windows 7
Windows 8

I want their contents to be

windows
Windows XP
Windows 7
Windows 8

After merging similar files they should look like

windows
Windows XP
Windows 7
Windows 8

continents
Europe
Asia
Africa

languages
English
Chinese

Please HELP !!


Solution

  • @echo off
    echo. >result
    for /f %%i in ('dir /b /a-d *.txt') do (
     echo.
     echo %%~ni
     type %%i
    )>>result
    ren result result.txt
    

    Pseude-Code for better understanding:

    turn echo off
    delete result file
    for all txt files in current directory do:
     print empty line
     print name of textfile without extension
     print textfile
    and put it into new file "result"
    if done, rename the resulting file