user3639557
user3639557

Reputation: 5281

How to concatenate files in sorted order?

I have a directory of files and I want to merge them. The only problem is that I want to merge them in the exactly same order that they appear by calling "ls -l".

Upvotes: 1

Views: 1251

Answers (2)

Myria
Myria

Reputation: 3797

cat `ls` > ../output.txt

output.txt must be in a different directory, or else the cat will fail.

Example run:

[myria@machine dir]$ echo Kitty > Kitty.txt
[myria@machine dir]$ echo Meow > Meow.txt
[myria@machine dir]$ echo Cat > Cat.txt
[myria@machine dir]$ echo Purr > Purr.txt
[myria@machine dir]$ cat `ls` > ../output.txt
[myria@machine dir]$ cat ../output.txt
Cat
Kitty
Meow
Purr

This may fail if the number of files is large. There are better solutions for esoteric cases, like noted in the comments.

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295308

The shell already sorts globs, out-of-the-box. Thus, for either:

# works only if the number of names is short enough to fit in one invocation
cat * >../output.txt

...or, its cousin with support for more names than will fit on a single command line...

# works for any arbitrary number of names
printf '%s\0' * | xargs -0 cat >../output.txt

...output is already sorted according to the collation order defined in LC_COLLATE (a variable which ls is also supposed to honor in any sorting it may perform).

Upvotes: 5

Related Questions