Saturday, August 18, 2001

Joining files

Suppose you have two files, say file1 and file2 which you want to put together in a single file, joint-file. There are two possible ways you might want to do that.
First, if you want file2 to be appended at the end of file1 you can execute this command:


cat file1 file2 > joint-file

On the other hand, if you want to join the files so that the lines of file2 are appended to the lines of file1, line by line, you can do


paste file1 file2 > joint-file

When might you need any of this options? Suppose each file has a list of users in your system and you want to put them together; then you can use cat. On the other hand, if your first file has the name of your users, and the second one the phone numbers (in the same order!), then you can use paste

An interesting option to paste is as follows:


paste -f file1 file2 > joint-file

The program will stop when one of the two files end; if they have the same number of lines, then -f will not make any difference, but if they are of different length (in terms of lines), you will get in the output file as many lines as the shortest file.