20

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...?

1
  • 2
    By the way, you might be interested in our new Bioinformatics site if you're working in the field.
    – terdon
    Aug 11, 2017 at 10:24

4 Answers 4

39

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
0
9

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.

3
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)
2

Try:

filedir="/path/to/files"
output="/path/to/all.pdb"
for file in $(find $filedir -type f -name "file.88_*" | sort -t "_" -k2 -n); do
    cat $file >> $output
done

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.

10
  • I still get the wrong order: 0 1 10 11 12... Aug 11, 2017 at 1:35
  • what os are you running? if you do sort --version what do you get? And you have the -n in the sort command right?
    – jesse_b
    Aug 11, 2017 at 1:36
  • OSX El Capitan, sort (GNU coreutils) 5.93 Aug 11, 2017 at 1:41
  • 1
    Thanks a lot for trying! The /dev/null addition to the other answer was much needed! Aug 11, 2017 at 1:52
  • 1
    Useless use of command substitution. Use something like find ... | sort ... | xargs cat >> $output instead. Aug 11, 2017 at 12:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .