In some cases, we need to split the file into several parts, for example, for easier storage. The easiest way to do this is with the split command in the Linux terminal.
In this article, I will explain how the Linux split command works. And then we will deal with specific use cases, for example, how to split a file into parts in Linux according to certain criteria.This command splits one file into several smaller ones. It has a fairly clear syntax. To split a file, you need to specify options, then the path to the large file and the path to create new files with a common prefix in the name:
split options /path/to/file /path/to/file/destination/prefix
Let's move on to the practical part, and with examples we'll see how the split command in Linux is used to split files by size, by number of lines, and into a given number of parts.
Split file by size
For example, we have an archive and it needs to be split into several files of 100 MB each. For convenience, let's prefix it with the archive_ name, where after the underscore there will be a suffix indicating the number of the final file. The command looks like this:
split -b 100M ~/test/archive.tar.gz ~/test/archive_
As a result, we get the following files:
Split file by number of lines
Sometimes you need to split one text document into several, for example, with the number of lines not exceeding the set number. The split command will look like this:
split -l 2 ~/test/file.txt ~/test/file_
In this example, we split a small text file into several, 2 lines each.
The result will look like this:
Split a file into a specified number of files
There may also be a situation where we need to split a file into a certain number of parts. In the example below, we cut our file into a maximum of 5 pieces using the -n option:
split -n 5 ~/test/archive.tar.gz ~/test/archive_
As a result, we get the following:
How to merge parts of a file
Now you know how to split a file into parts in Linux using the split command. The next step is to merge several parts into a single file. The cat command is perfect for this purpose. First you need to set the names of the parts themselves, and then the final file:
Let's merge the previously split files back into one archive:
cat ~/test/archive_* > ~/test/archive.tar.gz
As a result, we get the archive back:
The split utility can be very useful in some situations. It allows you to split one large file into several small ones using different options. We have covered several popular scenarios for its use. This article covers only the basics of working with the split command. You can find out more with the command: