Friday, 31 May 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

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

paste -s -d, file.txt

The out put will be as below:


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

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

Hope this helps somebody.



1 comment: