Skip to content

Linux Foundations / Find your way around Linux ยท Step 41 of 63

Lesson: join and splitSwitch
โ† Linux Foundations

Shell and files

join and split

Learn to combine files on a shared field with join and to break big files up with split.

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 dev

By 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.txt

This 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  xac

The 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.txt

cmp 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

  1. Create two small files that share ID numbers, in order.
  2. Join them, then add an ID to only one and try -a 1.
  3. Run seq 30 > n.txt and split -l 10 n.txt piece_.
  4. Rebuild with cat piece_* > m.txt and check with cmp.

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.