Home > Software engineering >  How to cat contents of multiple files from a python script
How to cat contents of multiple files from a python script

Time:12-12

I would like to cat the contents of the files generated from a python script. Is it possible to do that in a simple one line command? For example I would like to have something like:

cat <(python test.py) # doesnt work as I want to

where test.py produces multiple filenames like so (separated by new line)

file1.txt
file2.txt
file3.txt

I would like to basically do

cat file1.txt
cat file2.txt
cat file3.txt

Basically reading the contents of the filename produced by the script. Assume the python script can generate hundreds/thousands of filenames.

Though this may seem to work

cat $(python test.py)

But the problem is it seems to wait until the whole python test.py is completed, before it performs any cat. Basically it doesnt seem to cat the contents of the filename as soon as it gets a filename. Where as

cat <(python test.py)

cat the filename as it gets it, unfortunately, it just prints the filename but not the content of the filename.

CodePudding user response:

You could use sed

$ sed 's/^/cat /e' <(python3 test.py)

This will add cat in front of each filename before executing the command.

^ - This will anchor the find to the start of each line

cat - cat will replace the anchor at the start of each line

e - This tells sed to execute the commmand that resulted from the substitution, in this case cat file1.txt

  • Related