Skip to main content
close each file
Source Link
Gilles 'SO- stop being evil'
  • 865.3k
  • 205
  • 1.8k
  • 2.3k

You can use csplit. It does the job well, except that it's somewhat inflexible regarding the output file names (you can only specify a prefix, not a suffix) and you need a first pass to calculate the number of pieces.

csplit -f text -- input.txt '//' "{$(wc -l input.txt)}"
for x in text[0-9]*; do mv -- "$x" "$x.txt"; done

The GNU version, but not the OSX version, has extensions that solve both issues.

csplit -b '%d.txt' -f text -- input.txt '//' '{*}'

Alternatively, if csplit is too inflexible, you can use awk.

awk '{filename = sprintf("text%d.txt", NR); print >filename>filename; close(filename)}' input.txt

You can use csplit. It does the job well, except that it's somewhat inflexible regarding the output file names (you can only specify a prefix, not a suffix) and you need a first pass to calculate the number of pieces.

csplit -f text -- input.txt '//' "{$(wc -l input.txt)}"
for x in text[0-9]*; do mv -- "$x" "$x.txt"; done

The GNU version, but not the OSX version, has extensions that solve both issues.

csplit -b '%d.txt' -f text -- input.txt '//' '{*}'

Alternatively, if csplit is too inflexible, you can use awk.

awk '{filename = sprintf("text%d.txt", NR); print >filename}' input.txt

You can use csplit. It does the job well, except that it's somewhat inflexible regarding the output file names (you can only specify a prefix, not a suffix) and you need a first pass to calculate the number of pieces.

csplit -f text -- input.txt '//' "{$(wc -l input.txt)}"
for x in text[0-9]*; do mv -- "$x" "$x.txt"; done

The GNU version, but not the OSX version, has extensions that solve both issues.

csplit -b '%d.txt' -f text -- input.txt '//' '{*}'

Alternatively, if csplit is too inflexible, you can use awk.

awk '{filename = sprintf("text%d.txt", NR); print >filename; close(filename)}' input.txt
Source Link
Gilles 'SO- stop being evil'
  • 865.3k
  • 205
  • 1.8k
  • 2.3k

You can use csplit. It does the job well, except that it's somewhat inflexible regarding the output file names (you can only specify a prefix, not a suffix) and you need a first pass to calculate the number of pieces.

csplit -f text -- input.txt '//' "{$(wc -l input.txt)}"
for x in text[0-9]*; do mv -- "$x" "$x.txt"; done

The GNU version, but not the OSX version, has extensions that solve both issues.

csplit -b '%d.txt' -f text -- input.txt '//' '{*}'

Alternatively, if csplit is too inflexible, you can use awk.

awk '{filename = sprintf("text%d.txt", NR); print >filename}' input.txt