I want to read each line of a file and then take each line and produce a file with the lines data in it.

For example let say the file I want to read is named txt.txt and it has the below 4 lines:

data for the first row
data for the second row
data for the third row
data for the fourth row

I would like to produce 4 output files, each with a single line from the input file. So there would be 4 files that are produced after reading the input file. One named text1.txt (it would have the first line of data in it), one named text2.txt (it would have the second line of data in it), and so on.

  • split -l1 text inputfile. – DopeGhoti Jan 23 '19 at 22:49
  • 1
    Have you tried researching this? Reading a file one line at a time and output redirection is very common and there are a lot of resources online. – Peschke Jan 23 '19 at 22:51

One simple answer would be:

awk '{ print > "text"NR".txt"}' < input

This prints every line to a file that's named with your pattern; NR is a special variable in awk that contains the current line number.

With GNU split:

split -l1 --additional-suffix=.txt --numeric-suffixes=1 --suffix-length=1 input text

This splits the input file input one line at a time (-l1) into files with a prefix of text, with an additional suffix of .txt, with numeric suffixes starting at one and with no padding. Note that this method is limited to nine lines of input. If your filenames are flexible, you could drop the --suffix-length=1 option and the filenames would be named text01.txt .. text11.txt ..., which would get you up to 99 lines.

| improve this answer | |

Your Answer

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

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