Bash: How to Split Text File into Multiple Files


Often you may want to use Bash to split a large file into smaller files based on a specific number of lines.

You can use the following syntax to do so:

split -l 4 --additional-suffix=.txt cities.txt

This particular example splits the file named cities.txt into smaller files based on every 4 lines.

Here is what the various commands do:

  • -l: Specifies that the file should be split based on number of lines
  • 4: Specifies that the file should be split based on every 4 lines
  • –additional-suffix: Specifies the suffix to use for each resulting file

The following example shows how to use this syntax in practice.

Example: How to Split Text File into Multiple Files Using Bash

Suppose that we have a text file named cities.txt that contains the names of various U.S. cities.

We can use the cat command to view the contents of this file:

Suppose that we would like to split this text file into smaller files based on every four lines.

We can use the following syntax to do so:

split -l 4 --additional-suffix=.txt cities.txt

The following screenshot shows how to use this syntax in practice:

Bash split text file into multiple files

When we uses the ls command to view all of the files in the current directory, we can see that three new files were created:

  • xaa.txt
  • xab.txt
  • xac.txt

We can use the cat command to view the contents of each of these text files:

From the output we can see:

  • xaa.txt contains the first four lines from the teams.txt file.
  • xab.txt contains the next four lines from the teams.txt file.
  • xac.txt contains the next four lines from the teams.txt file.

Since the original teams.txt file contained 12 total lines, splitting the file on every four lines produced a total of three files with four lines each.

Also note that the original teams.txt file still exists in the current directory.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Find Duplicate Lines in File
Bash: How to Check if File is Empty
Bash: How to Compare Two Files
Bash: How to Check if File Contains Specific String

Leave a Reply