Trying to cat the result of piped commands

2

I have a folder of files that are named list20140801.txt list20140802.txt ....

I'm trying to do this

ls | sort | tail -3 | cat

But it is just giving me the file names, not cat'ing them.

Colton

Posted 2014-08-12T21:55:34.250

Reputation: 21

Answers

2

According to the cat manual, cat's job is to:

Concatenate FILE(s), or standard input, to standard output.

There is no reason why cat should treat its standard input as filenames. What you need is

ls | sort | tail -3 | xargs cat

instead.

Check xargs man page for more information: http://linux.about.com/library/cmd/blcmdl1_xargs.htm

AtomHeartFather

Posted 2014-08-12T21:55:34.250

Reputation: 236

as per @garyjohn's answer above, the sort is redundant in this simple case. – AtomHeartFather – 2014-08-12T22:25:13.297

0

The output of ls is already sorted by default in the same manner as sort sorts by default, so sort is not needed.

The most common way to pass a generated list of files to a command is to use xargs. See the xargs man page for details, but in this case you don't need any options. (xargs may not do what you want if you have a huge number of files, but in most common cases it works fine without you having to think about that.)

The version of tail used on many Linux systems these days does not accept just -3 as an option. It requires that you use -n3.

Finally, the cat at the end of your pipeline is not doing anything useful, so it can be omitted, too.

This command should do what you want.

ls | xargs tail -n3

Update

I just read @AtomicHeartFather's answer and realized that I may have put the tail with the wrong part of the problem. In that case, the command would be

ls | tail -n3 | xargs cat

which is pretty much what AtomicHeartFather wrote except for the sort.

garyjohn

Posted 2014-08-12T21:55:34.250

Reputation: 29 085