Unix Join Command Multiple Files
Linux and Unix join command tutorial with examples George Ornbo • • • Last updated Wednesday, Aug 10, 2016 Linux and Unix join command tutorial with examples Tutorial on using join, a UNIX and Linux command to join lines of two files on a common field. Examples of joining two files, sorting before joining, specifying a field separator and specifying the output format. Estimated reading time: 3 minutes Table of contents • • • • • • • • What is the join command in UNIX?
The join command in UNIX is a command line utility for joining lines of two files on a common field. It can be used to join two files by selecting fields within the line and joining the files on them. The result is written to standard output.
To combine several text files into a single file in Unix, use the cat command.
How to join two files To join two files using the join command files must have identical join fields. The default join field is the first field delimited by blanks. For the following example there are two files foodtypes.txt and foods.txt. Cat foodtypes.txt 1 Protein 2 Carbohydrate 3 Fat cat foods.txt 1 Cheese 2 Potato 3 Butter These files share a join field as the first field and can be joined. Join foodtypes foods. Leroy The Redneck Reindeer. txt 1 Protein Cheese 2 Carbohydrate Potato 3 Fat Butter How to join two files on different fields To join files using different fields the -1 and -2 options can be passed to join.
In the following example there are two files wine.txt and reviews.txt. Cat wine.txt Red Beaunes France White Reisling Germany Red Riocha Spain cat reviews.txt Beaunes Great!
Reisling Terrible! Riocha Meh These files can be joined by specifying the fields that should be used to join the files. Common to both files is the name of the wine. In wine.txt this is the second field.
In reviews.txt this is the first field. The files can be joined using -1 and -2 by specifying these fields. Join -1 2 -2 1 wine.txt reviews.txt Beaunes Red France Great! Reisling White Germany Terrible! Riocha Red Spain Meh How to sort before joining Join expects that files will be sorted before joining.