How to Combine All TXT Files in a Directory Using Windows CMD

The following Windows CMD command allows you to combine multiple .txt files into a single file.

This can be useful when working with with log files, or any scenario where you want to aggregate data.

This guide shows you how to do this using a one-liner command in Windows Command Prompt (CMD).

Requirements

  • Windows operating system
  • Basic understanding of the CMD interface

Instructions

  1. Open Command Prompt:
    • Go to the Start menu, type cmd, and hit Enter.
  2. Navigate to the Directory:
    • Use the cd command to navigate to the directory where your .txt files are located. For example:
      cd C:\path\to\your\directory
  3. Run the One-Liner Command:
    • Copy and paste the following command into CMD and then press Enter:

      for /r %i in (*.txt) do (echo %~nxi && type "%i") >> combined.txt

What Does the Command Do?

  • for /r %i in (*.txt): Iterates through all .txt files in the specified directory and its subdirectories.
  • echo %~nxi: Outputs the name and extension of the current file.
  • type "%i": Outputs the contents of the current file.
  • >> combined.txt: Appends the output to a file named combined.txt in the current directory.

Note: This command will not sort the files alphabetically before combining. If alphabetical sorting is crucial, you may need to use a more complex batch or PowerShell script.