2

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.

4

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

  • 1
    That assumes the file name doesn't contain space, tab, single quote, double quote or backslash characters though (and newline, but your usage of cut already seems to imply that) (and other blank characters in your locale with some xargs implementations). With GNU xargs, you can use xargs -rd '\n' cat to assume a newline delimited list of files. – Stéphane Chazelas Dec 9 '14 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.