How to concatenate two files in a new one and sort the output in one line

catsort

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?

Best Answer

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
Related Question