Terminal Command – How to Combine Multiple TXT Files into One

command lineterminaltext;

I'm trying to combine multiple txts into a big file. I want them to be put in sequence but this seems not to work properly.

At this time I tried from the terminal:cat *.txt >merged.txt but this seems to concatenate the files randomly.

In my folder I have all the files named with sequential numbers (from 1.txt to 10000.txt). Am I missing anything?

Best Answer

Globbing isn't random, it's guaranteed to be alphabetical (a.k.a. lexicographic order according to your locale), which is different from numeric sorting order.

You can use brace expansion for this. Replace '10' with the number of the last file.

cat {1..10}.txt > merged.txt

This uses bash brace expansion, which you can read about at LESS='+/Brace Expansion' man bash.

Note that unlike file globs, the brace expansion will generate arbitrary strings which need not be existing files; in this case that means you will get errors if there are files missing from the sequence (e.g. if 7.txt does not exist). However, this won't affect the contents of merged.txt which will be produced as expected.