These two tools work in opposite directions. join combines lines from two files that share a value, and split cuts one file into smaller pieces.
join on a common field
$ cat ids.txt
1 maya
2 omar
$ cat roles.txt
1 admin
2 dev
$ join ids.txt roles.txt
1 maya admin
2 omar devBy default join matches on the first field of each file, with fields separated by blanks.
Both files must be sorted on the join field, in the order sort uses for your locale. Otherwise matches can be missed, and GNU join may warn that the input is not sorted.
join options
Use -t for another separator and -1 and -2 to pick the join field in each file.
$ join -t ':' -1 2 -2 1 users.txt rooms.txtThis matches field 2 of users.txt with field 1 of rooms.txt.
Lines without a partner are left out. -a 1 also prints the unpaired lines from the first file.
split a large file
$ seq 2500 > big.txt
$ split big.txt
$ ls x*
xaa xab xacThe default is 1000 lines per piece, so the last holds 500. Names start with x.
Set the size with -l for lines or -b for bytes, and give your own prefix as a last argument.
$ split -l 1000 big.txt part_
$ ls part_*
part_aa part_ab part_ac
$ split -b 1M backup.tar chunk_GNU split also has -d for numeric suffixes such as part_00.
Put the pieces back
The shell expands the pattern in sorted order, so cat restores the file.
$ cat part_* > restored.txt
$ cmp big.txt restored.txtcmp prints nothing when the files are identical. Make sure the pattern matches only your pieces.
Try both tools in the streams and text lab.
Try it
- Create two small files that share ID numbers, in order.
- Join them, then add an ID to only one and try
-a 1. - Run
seq 30 > n.txtandsplit -l 10 n.txt piece_. - Rebuild with
cat piece_* > m.txtand check withcmp.
Check your understanding
join and split
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.