nerdizzle nerdizzle - 1 month ago 7
Bash Question

concatenate ordered files using cat on Linux

I have files from 1 to n, which look like the following:

sim.o500.1
sim.o500.2
.
.
.
sim.o500.n


Each file contains only one line. Now I want to concatenate them in the order from 1 to
n
.

I tried
cat sim.o500.* > out.dat
. Sadly this does not work if e.g.
n
is larger than 9, because this concatenates then
sim.o500.1
followed by
sim.o500.10
and not
sim.o500.1
followed by
sim.o500.2
.

How can I loop through the file names using the numeric order?

Answer

Since * expands in a non-numeric-sorted way, you'd better create the sequence yourself with seq: this way, 10 will coome after 9, etc.

for id in $(seq $n)
do
   cat sim.o500.$id >> out.dat
done

Note I use seq so that you are able to use a variable to indicate the length of the sequence. If this value happens to be fixed and known beforehand, you can directly use range expansion writing the n value like: for id in {1..23}.