Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Say, I have a command command which prints huge number of lines to stdout:


I want to save the output to disk, but not as a single file, but as a sequence of files each having 1000 lines of stdout:




I've tried to google the answer, but every time google points me to tee command, which is useless in this situation. Probably, I'm entering wrong queries.

share|improve this question
up vote 22 down vote accepted

Once you are done saving the file, you could always split the file into file pieces or multiple files based on the number of lines.

split -l 1000 output_file

or even better just try

command | split -l 1000 -

This will split the output stream into files with each 1000 lines (default is 1000 lines without -l option).

The below command will give you additional flexibility to put or enforce a prefix to the filename that will be generated when the output is generated and splitted to store into the file.

command | split -l 1000 - small-

share|improve this answer

You can use a bash script lines.bash

while IFS='' read -r line
  printf -v filename "%04d.txt" "$((a++/1000))"
  echo "$line" >> $filename

and use it as:

cat long_file.txt | bash lines.bash

The only problem I noticed is with * sign in long_file.txt (somebody could correct it).

share|improve this answer
Set the IFS to empty string to avoid word splitting on read. Use -r to disable backslash escaping on read. Remove -e to avoid backslash escaping on echo. Use quoting to avoid word splitting on echo. Use -v in bash since 4.0 to avoid starting a sub-process. Use post-incrementing as your current code will put in the first file only 999 lines. a=0; while IFS='' read -r line; do printf -v filename "%04d.txt" $((a++/1000)); echo "$line" >> "$filename"; done – manatwork Dec 6 '11 at 14:09
@manatwork Thank you. Only my printf does not have -v switch. (bash 4.2.10). At least it's not in manpage of printf – xralf Dec 6 '11 at 14:21
man printf documents /usr/bin/printf, that could never in life set an environment variable. See help printf for the printf shell built-in's documentation. – manatwork Dec 6 '11 at 14:44
@manatwork OK. There seems to be syntax error in the ++/ part yet. – xralf Dec 6 '11 at 14:48
One more thing: there is no need to use sigil inside arithmetic evaluation, unless you need parameter expansion explicitly. In arithmetic expansion the variables are evaluated anyway. – manatwork Dec 6 '11 at 14:49

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.