Skip to Content

How to concatenate multiple text files into one

Command Line

Have you ever wanted to merge a bunch of text files together into one large one? For example, if you use a tool to go grab a bunch of show command results and output it to a text file per device, it's handy if you can have the operating system merge all that together for you. Many of you have likely done this at one point or another, but I figured it was worth capturing here to share the syntax.

So, if you are in a Windows command prompt, you can use the type command to output the contents of a file.

C:\>type text1.txt
This is a test. 

Then you can use the type command plus the double arrows to merge a bunch of files:

C:\>type *.txt >> merge.txt

text1.txt

text2.txt

text3.txt

text4.txt

This leaves you with all the original files plus a new one called merge.txt. Piece of cake.

If you are in Linux, you can similarly redirect console output and merge files using the cat command:

cat *.txt >> merged.txt

That's it for this post. If you have a cool command line way of working with files, feel free to share in the comments below!

Your rating: None Average: 4.9 (10 votes)

Comments

Here's a one-liner that takes

Here's a one-liner that takes installed packages on a RHEL style system and puts them into a one line text file which can be fed into a yum install on a similar deployment. Perhaps could be cleaner but the point of the comment is don't forget while >> appends > overwrites.
The cut command removes un-needed text, sed adds a space to the end of each line and tr (translate) removes all of the end of line characters making the multiline text file into one line of text.

yum list installed | cut -d' ' -f 1 | sed 's/$/ /' | tr -d '\n' > installed-packages

you can also use the copy command

you can also use the copy command to do this :)

ie.

one.txt
two.txt
three.txt

Copy /B *.txt combined.txt

you can omit the /B this is just to copy in binary mode.

FINDSTR this is another good

FINDSTR

this is another good command you can use to search inside text files.

for example

FINDSTR "10.45.76.3" config*.txt

will search all txt files starting with the file name config... for the string "10.45.76.3" and output the file name and the line containing the value.

There are lots of arguments you can use including one that just gives you the file names of matching files.

You can find them all on this site, which I came across years ago but am always finding new stuff.

http://ss64.com/index.html

Defiantly worth having a look and yo will add it to your Favorites believe me. :)

CLI

Until windows has a comparable CLI to *nix I can't see myself getting into this. My biggest gripe is traceroute vs tracert. I really wish they'd upgrade this feature already.



Dr. Radut | blog