Command that prints file contents given filename on stdin
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 videos on Youtube
RobV
Updated on September 18, 2022Comments
-
RobV almost 2 years
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 ascat
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
withecho 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 getcat
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. -
Stéphane Chazelas over 9 yearsThat 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 somexargs
implementations). With GNUxargs
, you can usexargs -rd '\n' cat
to assume a newline delimited list of files.