search

Loading

Friday, May 31, 2013

How to join all lines in a file using comma as delimiter?

Sometimes we want to combine the lines in a file as single line. How to achieve this in linux using command line?

We can use the command 'paste' for this purpose.

From its man page,

paste - merge lines of files


For example, we have a file called file.txt and all its contents are in separate line.

cat file.txt
line1
line2
line3
line4


To merge this into comma separated single line use below command:

paste -s -d, file.txt

The out put will be as below:

line1,line2,line3,line4

What if you want to save it into another file say, file2.txt

 paste -s -d, file.txt > file2.txt

The output will be as below:

cat file2.txt
line1,line2,line3,line4


In paste command, -d is used to set the delimiter. Here we uses comma (,) as delimiter but you can use anything you like.

How to join lines without any delimiter?

paste -s --delimiter="" file.txt
line1line2line3line4



Hope this helps somebody.

                                                                               

Reference

No comments :

Post a Comment