Command that prints file contents given filename on stdin

catstdinxargs

I have a command that produces some output part of which is actually a file name containing the full output data. I want to extract the file name (which I trivially do with cut) and then pass it to another program such as cat which will display the contents of that file.

I can't share the actual command I am running but for the purposes of reproducibility you can replace ./my-command args with echo 1:2:3:4:file.txt

So I tried the following:

./my-command args | cut -d : -f 5 | cat

However this just prints the file name since cat merely copies the contents of stdin (which contains my filename) to stdout when it is invoked without any arguments.

Now I know that I can work around this is Bash by inverting the flow of commands and essentially passing cat the argument via a sub-shell e.g.

cat `./my-command args | cut -d : -f 5`

And this will print the contents of the file however this is not particularly friendly since I can't simply pipe the output of my underlying command by appending a simple command to my invocation.

Is there a cat like program which will take in filenames on stdin and print their contents? Or is there a way to get cat to treat stdin as arguments?

Notes

I realise that I could define a bash function that would read filenames from stdin and invoke cat on them in my own environment. However this technique for dumping the output data directly needs to be included in end user documentation and a simple shell agnostic approach is highly preferable.

Best Answer

After doing a bit more research I realised that this scenario is exactly what xargs is designed for:

./my-command args | cut -d : -f 5 | xargs cat

Which will transform the output of stdin into an invocation of cat with an actual filename and thus print out the file contents

Related Question