Shell – Split the lines of a text file into separate files

shell-scriptsplittext processing

I have a text file that looks something like this:

foo
bar
zip
rar
tar

I need to use a bash script on OSX to make a new text file after every new line like this:

cat text1.txt
foo
cat text2.txt
bar
cat text3.txt
zip
cat text4.txt 
rar
cat text5.txt
tar

Best Answer

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
Related Question