Operating System - HP-UX
1748140 Members
3563 Online
108758 Solutions
New Discussion юеВ

Re: Join lines into one line

 
SOLVED
Go to solution
wojtek75
Frequent Advisor

Join lines into one line

Hi,

I have a text file which includes undefined number of lines as follows:
====file.txt====
line1
line2
line3
line4
[...]
lineN
============

What command should I use to have the output like that:
line1,line2,line3,line4,[...],lineN

awk is very welcome. Thanks in advance


12 REPLIES 12
Matti_Kurkela
Honored Contributor

Re: Join lines into one line

tr '\n' ',' < file.txt

MK
MK
Steven Schweda
Honored Contributor
Solution

Re: Join lines into one line

> tr '\n' ',' < file.txt

And, to trim off the final comma:

< file.txt tr '\n' ',' | sed -e 's/,$//'
Viktor Balogh
Honored Contributor

Re: Join lines into one line

or

# cat file.txt | xargs
****
Unix operates with beer.
wojtek75
Frequent Advisor

Re: Join lines into one line

xargs uses space ' ' instead of comma.
Viktor Balogh
Honored Contributor

Re: Join lines into one line

.. if you want it comma-separated:

# cat file.txt | xargs | tr " " ","
****
Unix operates with beer.
Viktor Balogh
Honored Contributor

Re: Join lines into one line

> awk is very welcome. Thanks in advance

here is your AWKward solution:

# awk '{printf $0","} END {print}' file.txt
****
Unix operates with beer.
Steven Schweda
Honored Contributor

Re: Join lines into one line

> # cat file.txt | xargs | tr " " ","

Not so good if the lines contain spaces:

dyi # cat file.txt
line 1
line 2
line 3

dyi # cat file.txt | xargs | tr " " ","
line,1,line,2,line,3

But (this time on a real HP-UX system):

dyi # ( tr '\n' ',' ; echo '' ) < file.txt | sed -e 's/,$//'
line 1,line 2,line 3


(Some "sed" programs don't do well with
unterminated lines, I see. Everything's
complicated.)
Steven Schweda
Honored Contributor

Re: Join lines into one line

> # awk '{printf $0","} END {print}' file.txt

Around here, that still has the extra comma
at the end:

dyi # awk '{printf $0","} END {print}' file.txt
line 1,line 2,line 3,

(But it does better with embedded spaces.)
Viktor Balogh
Honored Contributor

Re: Join lines into one line

> Around here, that still has the extra comma
at the end

nope, on my linux box it duplicates the last line and so I didn't end up with an extra comma. I just didn't recognize the duplicate.

basically I wanted this version, but somehow the reference to the last line didn't work:

# awk 'NR != "$NR" {printf $0","} END {print}' test

so I ended up with this:

# awk '!(NR-1) {printf $0} NR-1 {printf ","$0} END {print ""}'

which works on linux. (too sad I don't have an HP-UX access at the moment :(
****
Unix operates with beer.