PowerShell: How to Split File by Number of Lines


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

You can use the following syntax to do so:

$i=0; Get-Content $my_file -ReadCount 3 | %{$i++; $_ | Out-File out_$i.txt}

This particular example splits the file specified at the path stored in the variable named $my_file based on every 3 lines and names the resulting output files out_1.txt, out2.txt, etc.

To split the file based on a different number of lines, simply change the 3 after the -ReadCount parameter to a different number.

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

Example: How to Split File by Numbers of Lines Using PowerShell

Suppose that we have a file located at the following path:

  • c:\users\bobbi\data3\teams.txt

This file currently contains information about nine professional basketball teams:

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

We can use the following syntax to do so:

$my_file = 'c:\users\bobbi\data3\teams.txt'

$i=0; Get-Content $my_file -ReadCount 3 | %{$i++; $_ | Out-File out_$i.txt}

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

PowerShell split file by lines

We can see that we were able to successfully split the teams.txt file based on every three lines, which resulted in a total of three files being created in the current directory:

  • out_1.txt
  • out_2.txt
  • out_3.txt

We can use the Get-Content cmdlet to view the contents of each of these text files:

From the output we can see:

  • out_1.txt contains the first three lines from the teams.txt file.
  • out_2.txt contains the next three lines from the teams.txt file.
  • out_3.txt contains the next three lines from the teams.txt file.

Since the original teams.txt file contained nine total lines, splitting the file on every three lines produced a total of three files with three 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 PowerShell:

PowerShell: How to Delete All Files with Specific Extension
PowerShell: How to Rename File Extension of Multiple Files
PowerShell: How to Add Date to File Name

Leave a Reply