0

I have a file of many groups of lines, with blank line separating the "groups" of lines. I want to put each group of lines into one line separated by space.

input

line1
line2
line3
---blank line-
lineA
lineB
---blank line-
line$
line%
line&
line£

output

line1 line2 line3
lineA lineB
line$ line% line& line£
4
  • Do you have python installed on your system (type 'python' in to the CLI and if it opens, you do. To exit type: 'exit()' ) – Abraxas Jan 15 '16 at 18:26
  • Also, can you clarify your desired output? Would it be, for a group of 3 lines and a group of two lines something which looks like: line1line2line3 line4line5 ? Or do you want all lines in a group on one line and then a newline for the next group of lines? – Abraxas Jan 15 '16 at 18:33
  • yes I have python, each group has different number of lines and as you understood I want all lines of the same group in one line and a new line for the next group etc. – Mohsen El-Tahawy Jan 15 '16 at 19:13
  • I agree with Abraxas. How about you show us the results of a manually-performed example, rather than try to describe the results? – TOOGAM Jan 15 '16 at 19:19
1

Since comments suck for formatting, please verify this is the correct input/output format desired:

InputFile.txt:

Iamline1
Iamline2
Iamline3
GrouponeEndswithme

Group2startshere
Thisisgroup2line2

OUTPUTFILE.txt:

Iamline1Iamline2Iamline3GrouponeEndswithme Group2startshereThisisgroup2line2

In this case your output file with ALL groups is still only ONE line, not multiple lines. This would also mean that ANY spaces in lines in your groups of lines would look indistinguishable from a 'new group' in the output file. If this is not your desired format PLEASE provide a sample input and ouput in your question description.

Per your description, here is a script which will create your file. Please make sure to modify the 'open('filename.txt', 'r')' with the correct filename.

#Line Formatter

newfile = open('newfile.txt', 'w+')

with open('filename.txt', 'r') as f:
    group = ""
    for line in f:
        if len(line) > 0:
            group += line + " "
        else:
            group = group + "\n"
            newfile.write(group)

newfile.close()

Per @MohsenEl-Tahawy here is his perl solution:

perl -00ne 's/\n/ /g;print "$_\n";' inputfile
2
  • thank you I have found the answer perl -00ne 's/\n/ /g;print "$_\n";' inputfile – Mohsen El-Tahawy Jan 15 '16 at 19:46
  • @MohsenEl-Tahawy Nice, I have provided a script as well. I'd recommend submitting the perl solution as an answer or marking my answer and I'll include your script as well so that future searches will find a solution. Thanks – Abraxas Jan 15 '16 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.