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?
2 Answers
You have already redirected the output of file1
and file2
to the new file file3
.
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 file1
and 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 tee
command.
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 tee
:
sort $opts file[12] | tee output_file
-
-
@Ramesh A lot of standard UNIX commands take files as arguments. People overuse
cat
so much that there are actually pages listing redundant usages of it. Here's one such page: en.wikipedia.org/wiki/Cat_%28Unix%29#Useless_use_of_cat– gparentOct 16, 2014 at 20:17 -
@gparent, I think you have put the comment in the wrong place. And anyways, the point you refer to is a valid point and I have got rid of the useless use of cat. And I believe the
zsh
andtee
approach in the answer should be effective and they do not overuse the cat.– RameshOct 16, 2014 at 20:21 -
Ah, on my end I still see usage of
cat | sort
rather thansort
. My bad.– gparentOct 16, 2014 at 20:24