views:

697

answers:

5

Let's say you got a file containing texts (from 1 to N) separated by a $ How can a slit the file so the end result is N files?

text1 with newlines $
text2 $etc... $
textN

I'm thinking something with awk or sed but is there any available unix app that already perform that kind of task?

+2  A: 

Maybe split -p pattern?

Hmm. That may not be exactly what you want. It doesn't split a line, it only starts a new file when it sees the pattern. And it seems to be supported only on BSD-related systems.

You could use something like:

awk 'BEGIN {RS = "$"} { ... }'

edit: You might find some inspiration for the { ... } part here:

http://www.gnu.org/manual/gawk/html_node/Split-Program.html

edit: Thanks to comment from dmckee, but csplit also seems to copy the whole line on which the pattern occurs.

Bill Karwin
Hmmm, my `split` doesn't have a `-p` option - what OS is that on?
Ken Gentle
Mac OS has it. Also consider "csplit".
dmckee
I'm on Mac OS X, which is based on BSD UNIX. See http://www.freebsd.org/cgi/man.cgi?query=split
Bill Karwin
I'd figured out the RS part of the awk script it's the "..." part that still puzzled me. BTW, split doesn't have -p on cygwin.
Julien Grenier
Cygwin is based on GNU, not BSD. But it doesn't matter, split -p isn't what you want.
Bill Karwin
See link above to a GNU awk program that splits into multiple files.
Bill Karwin
A: 

If I'm reading this right, the UNIX cut command can be used for this.

cut -d $ -f 1- filename

I might have the syntax slightly off, but that should tell cut that you're using $ separated fields and to return fields 1 through the end.

You may need to escape the $.

R. Bemrose
+1  A: 

awk 'BEGIN{RS="$"; ORS=""} { textNumber++; print $0 > "text"textNumber".out" }' fileName

Thank to Bill Karwin for the idea.

Edit : Add the ORS="" to avoid printing a newline at the end of each files.

Julien Grenier
A: 
awk -vRS="$" '{ print $0 > "text"t++".out" }' ORS="" file
ghostdog74
A: 

using split command we can split using strings.

but csplit command will allow you to slit files basing on regular expressions as well.

Venkataramesh Kommoju