How to redirect the output of 'cat' into a different folder?

I have a Python script, EulerianCycle.py, and an input file, euleriancycle.txt.

I am able to get the correct results by doing py EulerianCycle euleriancycle.txt > cat euleriancycleout.txt into the current folder (py is an alias for python3).

However, I have another folder in this current one called outputs, to which I want all my output files be directed.

I've tried py EulerianCycle.py euleriancycle.txt | cd outputs/ | cat > euleriancycleout.txt

And py EulerianCycle.py euleriancycle.txt | cat >cd outputs/euleriancycleout.txt

which gives me the broken pipe error.


Solution 1:

If py EulerianCycle.py euleriancycle.txt writes to the standard output stream (which I assume it does, since otherwise you wouldn't be able to pipe it to cat) then cat is entirely superfluous here - you can redirect standard output directly, specifying either absolute or relative path to your output file:

py EulerianCycle.py euleriancycle.txt > outputs/euleriancycleout.txt

(note: the directory outputs/ must already exist).


Neither of your other commands works the way you might imagine.

  • in py EulerianCycle euleriancycle.txt > cat euleriancycleout.txt, the shell creates a file named cat in the current directory, and redirects the output of py EulerianCycle to it, passing both euleriancycle.txt and euleriancycleout.txt to it as input arguments.

  • in py EulerianCycle.py euleriancycle.txt | cat >cd outputs/euleriancycleout.txt, the shell creates a file named cd in the current directory, cat reads outputs/euleriancycleout.txt and writes it to file cd, ignoring standard input from the pipe (cat only reads standard input when it is given no input files, or an explicit -).

Perhaps what you were aiming for here was to pipe the output to a subshell like:

py EulerianCycle.py euleriancycle.txt | (cd outputs; cat > euleriancycleout.txt)

or

py EulerianCycle.py euleriancycle.txt | (cd outputs && cat > euleriancycleout.txt)

Here, cat reads the subshell's standard input - which is provided by the pipe - after changing to the target directory. The second version only creates euleriancycleout.txt if the cd command succeeds; the first creates it in the current directory if the cd fails.

Solution 2:

Additionally, you can use:

EulerianCycle.py | tee euleriancycleout.txt

to send the content to the text file and to stdout concurrently in 2 seperate streams. In other words the content will end up both in the text file and printed in the terminal.

I always do it this way as it shows me what wrote, and saves me having to open up vim to check my work.