cat files in specific order based on number in filename

I have files named file.88_0.pdb, file.88_1.pdb, ..., file.88_100.pdb. I want to cat them so that file.88_1.pdb gets pasted after file.88_0.pdb, file.88_2.pdb after file.88_1.pdb, and so on. If I do cat file.88_*.pdb > all.pdb, the files are put together in the following order: 0 1 10 11 12 13 14 15 16 17 18 19 2 20..., etc. How do I put them together so that the order is 0 1 2 3 4 5 6...?

Asked By: sodiumnitrate



for file in $(find $filedir -type f -name "file.88_*" | sort -t "_" -k2 -n); do
    cat $file >> $output

This was able to sort the files on by the (-k2) second field using _ as a separator. Here you have to use >> otherwise each new file will overwrite the last.

Answered By: jesse_b

Use brace expansion

cat file.88_{0..100}.pdb >>bigfile.pdb

To ignoring printing the error messages for non-existent files use:

cat file.88_{0..100}.pdb >>bigfile.pdb 2>/dev/null

In the zsh shell also you have the (n) globbing qualifier to request a numerical sorting (as opposed to the default of alphabetical) for globs:

cat file.88_*.pdb(n) >>bigfile.pdb 2>/dev/null
Answered By: αғsнιη
cat $(for((i=0;i<101;i++)); do echo -n "file.88_${i}.pdb "; done)

or, regarding the comment of Jesse_b:

cat $(for((i=0;i<101;i++)); do test -f "file.88_${i}.pdb" && echo -n "file.88_${i}.pdb "; done)
Answered By: Hauke Laging

In shell w/o brace expansion, if you file names don’t contain whitespace, quotes nor backslashes, you can use ls (assuming the GNU implementation) + xargs:

ls -v file.88_*.pdb | xargs cat > all.pdb

ls will sort files in numeric order:

-v natural sort of (version) numbers within text.

Answered By: Alexander Kovalev
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.