16

Is there a utility that split file by newline symbol? e.g if a file contains the following lines,

aa
bbb
cccc

If I want to split it to 3 files, the desired output would be:

aa, bbb And cccc (in 3 different files)

I already checked the split command, it only cut file by file sizes, not what I want.

If I don't wrote a utility myself, is there any standard tool to use?

3

3 Answers 3

20

Unless I'm missing something, split does split by line if you use -l switch:

   -l, --lines=NUMBER
          put NUMBER lines per output file

so

split -l 1 inputfile

should do what you want.

0
4
awk '{print > $0".txt" }'  inputfile

would create one file per unique line in inputfile named after the content of those lines (with a .txt extension). But beware that when the limit of concurrent open files is reached, some awk implementations will fail.

Or

awk '{f = "output_file." NR; print $0 > f; close(f)}' inputfile

To have numbered output files.

2
  • You may want to close() the output file after it's written, otherwise you'll run into the maximum number of open files limit with most awk implementations. Apr 30, 2013 at 11:47
  • don't aware of that.. can you do that for me ? thanks.. Apr 30, 2013 at 11:49
3
A=0
while IFS= read -r LINE ; do
  printf '%s\n' "$LINE" > newfile$A
  (( A++ ))
done < "$INPUTFILE"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .