Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

At the Linux/Unix command line, I want to turn this:

A
B
C
A
B
C
.
.
.

into this:

A,B,C
A,B,C
...

Is there a simple built-in command to do this, or does this require diving into Awk, Perl, etc.?

share|improve this question

3 Answers 3

up vote 6 down vote accepted

Don't know such built-in. Using Bash you can:

while read a && read b && read c ; do echo $a,$b,$c ; done < file
share|improve this answer
    
If you have only 5 lines, you may not want to lose lines 4 and 5 just because you don't have line 6. –  musiphil Oct 16 at 17:19

That is horrible, surely something like

tr \\n ' '

would do the same thing?

So for e.g. to join lines of the file *file_lines* use

cat file_lines | tr \\n ' '
share|improve this answer
3  
He didn't want all of it on a single line, it seems. –  l0b0 Feb 17 '12 at 10:42
    
Exactly. Referencing the problem statement, this would produce a single line with everything on it (A B C A B C A B C A B C A B C ...) which is not what was requested. –  Alan Krueger Feb 17 '12 at 17:08

Here is a solution in python:

#!/usr/bin/python3

def njoin(filename, outfn="", n=3, linesuffix=" "):
    if not outfn:
        outfn = filename + ".join"
    with open(filename) as infh, open(outfn, "w") as outfh:
        nline = 0
        for line in infh:
            if nline % n != n-1:
                line = line.rstrip() + linesuffix
            outfh.write(line)
            nline += 1

In your case you can use the function like this:

njoin("/path/to/file", n=3, linesuffixe=",")
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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