Skip to main content

Split files on lines

Split the file into multiple files at every 3rd line . i.e, First 3 lines into F1, next 3 lines into F2 and so on:

$ awk 'NR%3==1{x="F"++i;}{print > x}' filename

In other words, this is nothing but splitting the file into equal parts. The condition does the trick here: NR%3==1 : NR is the line number of the current record. NR%3 will be equal to 1 for every 3rd line such as 1st, 4th, 7th and so on. And at every 3rd line, the file name is changed in the variable x, and hence the records are written to the appropriate files.