8

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

3 Answers 3

11

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
2
  • awk: text18.txt makes too many open files input record number 18, file ~/Desktop/namnlös mapp/flash varibales3.txt source line number 1 Commented Oct 30, 2014 at 12:34
  • @DisplayName Ooops yes, files need to be closed. Edited. Commented Oct 30, 2014 at 12:53
2

Version with pure bash...

unset i; while read -r l; do echo $l > "text$((++i)).txt";done < text_file.txt
1

Assuming the contents of the text file contains no spaces you could also use a for loop in Bash.

$ for x in $(<file.txt); do echo "$x" > text$((++i)).txt; done

Example

$ cat file.txt 
foo
bar
zip
rar
tar

Now with $i unset.

$ unset i
$ for x in $(<file.txt);do echo "$x" > text$((++i)).txt;done
$ ls -l text*
-rw-rw-r--. 1 slm slm 4 Oct 29 22:03 text1.txt
-rw-rw-r--. 1 slm slm 4 Oct 29 22:03 text2.txt
-rw-rw-r--. 1 slm slm 4 Oct 29 22:03 text3.txt
-rw-rw-r--. 1 slm slm 4 Oct 29 22:03 text4.txt
-rw-rw-r--. 1 slm slm 4 Oct 29 22:03 text5.txt

Confirming the results:

$ head text*
==> text1.txt <==
foo

==> text2.txt <==
bar

==> text3.txt <==
zip

==> text4.txt <==
rar

==> text5.txt <==
tar

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.