Raphael Burkhardt
Raphael Burkhardt

Reputation: 3

How to connect the output of a bash command to cat?

I'm trying to connect the output of a "find" command to a "cat" command:

find -size 8c
returns ./test.txt (it's my only file with a size of 8 bytes in this folder)

cat ./test.txt
returns iamatest (The content of test.txt)

But when I try to connect the two:
find -size 8c | cat
It returns ./test.txt the name of the file and not it's content. I must be missing something: I want find to pass it's output as an input to cat.

I also tried cat <(find -size 8c) but it also returns the name of the file instead of the content.

Upvotes: 0

Views: 177

Answers (3)

dmadic
dmadic

Reputation: 477

What is wrong with your solution?

You got ./test.txt as an output for find -size 8c | cat because cat without parameters is alias for cat /dev/stdin. It means cat just prints whatever it got as standard input.

One way to solve it

One possible solution for your problem is to use xargs command. It gives you an option to pass standard output of one command as command line argument(s) of another one.

Since this definition is pretty general, let me explain it on your example.

find -size 8c | xargs cat

will output:

iamatest

What xargs did here?

It passed standard output of find -size 8c which is ./test.txt as command line argument of cat making it exactly the same as cat ./test.txt.

If you have more than one 8 byte file

If you had another file test_2.txt with 12345678 as content find -size 8c will give you:

./test.txt
./test_2.txt

Calling find -size 8c | xargs cat will give you:

iamatest12345678

Which is exactly the same as if you run cat ./test.txt ./test_2.txt

Upvotes: 0

SteveK
SteveK

Reputation: 995

You can call cat on the find command's output:

cat $(find -size 8c)

This gets turned into

cat test.txt

(assuming that's the only result)

Upvotes: -2

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47169

You can use the -exec option of find:

find . -size 8c -exec cat {} \;

If you want to limit the depth use:

find . -size 8c -maxdepth 1 -exec cat {} \;

Upvotes: 5

Related Questions