Celeb Glow
general | March 14, 2026

Split a file into two files at a given line

I'm looking for a way in unix to split a file into two files at a given line number.

split -l 100 file_name is close to what I'm looking for, but this command creates multiple files, each of 100 lines. I'm looking for a command to split a file into two files at a given line number. Is there a way to do this in unix?

6 Answers

A bit tighter solution:

(head -100 > f1.txt; cat > f2.txt) < input.txt
3

Use awk, so that you need to make just one pass through the input file. The following assumes you want the first 122 lines in the first file, and the remainder in the second.

awk 'NR < 123 { print >> "top_file"; next } {print >> "bottom_file" }' file_name
3

You can use head and tail to get both parts:

head -n K file_name > top_file
tail -n L file_name > bottom_file

where K is the line number, and L is number of lines from the bottom (total number of lines - K).

(you can get the total number of lines using wc -l file_name).

You could use csplit (if available) to do it:

csplit file N+1

will split the file into two pieces, one piece up to (and including) line number N and the other piece from line number N+1 up to the last line.
If you want to split up to (but not including) line number N:

csplit file N
4

Both head and tail have options to produce lines from the "other" end of the file than they otherwise would. So you have these two options:

head -n 100 source.txt > file1.txt
head -n -100 source.txt > file2.txt

or (where NNN is 100 less than the output of wc -l source.txt):

tail -n +NNN source.txt > file1.txt
tail -n NNN source.txt > file.txt

You can read the manual pages for your versions of head and tail for more information.

You can use 'wc', 'dc', 'head' and 'tail'. I.e.

unix> wc -l foo
545 /tmp/foo
unix> dc -e '545 100 - p'
445
unix> head -n 100 foo > filea
unix> tail -n 445 foo > fileb

For ease of use, you can turn above into a shell script.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy