How to merge all (text) files in a directory into one?

This is technically what cat ("concatenate") is supposed to do, even though most people just use it for outputting files to stdout. If you give it multiple filenames it will output them all sequentially, and then you can redirect that into a new file; in the case of all files just use * (or /path/to/directory/* if you're not in the directory already) and your shell will expand it to all the filenames

$ cat * > merged-file

If your files aren't in the same directory, you can use the find command before the concatenation:

find /path/to/directory/ -name *.csv -print0 | xargs -0 -I file cat file > merged.file

Very useful when your files are already ordered and you want to merge them to analyze them.


More portably:

find /path/to/directory/ -name *.csv -exec cat {} + > merged.file

This may or may not preserve file order.


The command

$ cat * > merged-file

actually has the undesired side-effect of including 'merged-file' in the concatenation, creating a run-away file. To get round this, either write the merged file to a different directory;

$ cat * > ../merged-file

or use a pattern match that will ignore the merged file;

$ cat *.txt > merged-file