I have two files with some names in them, when I ran
cat file1 file2 | sort, the terminal shows the names sorted alphabetically, but when I run
cat file1 file2 > file3 | sort I don't see the sorted output, why?
You have already redirected the output of
file2 to the new file
With this command
cat file1 file2 > file3 | sort,
sort after pipe.
This could be verified as below.
cat file1 A Z B cat file2 F G C
Now when I run the command as,
cat file1 file2 > file3 | sort we could see that the contents of
file2 are written to
file3 but it is not sorted.
I believe what you are trying to achieve could be fairly easily accomplished as,
cat file1 file2 | sort > file3
However, it doesn't show the output in the console window.
If you need the output of two files after sorted to be written to a new file and at the same time the sorted output to be available in the console, you could do something like below.
cat file1 file2 | sort > file3; cat file3
However, it is good to make use of
tee in this case.
tee could be effectively used as,
cat file1 file2 | sort | tee file3
The above command basically concatenates 2 files and sorts them and displays the output in the console and at the same time writes the output of the pipe to the new file specified using the
As user casey points out, if you have
zsh shell available on your system, you could use the below command as well.
sort <file1 <file2 | tee file3
POSIX defines the
sort utility's purpose so:
Sort lines of all the named files together and write the result to the specified output.
You can sort two files into a concatenated output file like:
sort $opts file1 file2 >output_file
If you want to see the output on your shell's
stdout and save the results in an output file then use
sort $opts file | tee output_file