Flat file to csv conversion

Hi Guy's can someone help me in converting the following

I have a flat text file which has several thousand lines which I need to convert to a csv it's got a consistent format but basically want every time it hit's txt to create a new line with the subsequent lines comma delimited for example

txt.1,line 1, line 2, line n
txt.2,line 1, line 2, line n
etc 

The input file looks like this

txt.1
line 1
line 2
line n
txt.2
line 1
line 2
line n
txt.n
line n

Thanks All

>cat p1.txt
txt.1
line 1
line 2
line n
txt.2
line 1
line 2
line n
txt.n
line n

>sed 's/txt/~txt/g' <p1.txt | tr "\n" "," | tr "~" "\n" | sed 's/,$//'

txt.1 ,line 1 ,line 2 ,line n
txt.2 ,line 1 ,line 2 ,line n
txt.n ,line n

Perfect - thank you very much!!!!

Or with awk:

awk '/txt/{if(s){print s}{s=$0;next}}{s=s "," $0}' file

One last question - my fault for not being precise - what if the file name varies the other way ie

1.txt
2.txt

this produces slightly different result for sed, and awk is only providing one result for the file

The given command should work, but to be more precise, if the lines are ending with txt you can use the $ anchor:

awk '/txt$/{if(s){print s}{s=$0;next}}{s=s "," $0}' file

More about anchors:

Regexp Operators - The GNU Awk User's Guide

One in perl,

perl -lne '$\=""; $v =(/^txt/)?"\n$_":" $_"; print $v;' file