Some examples of how to use the paste command

The paste command, by its definition, is used to merge lines of files. This is a useful tool for mergin a single file and also set of files. In this articles, we will see how to use the paste command for handling both a single file and multiple files.

Use paste with a single file

Let's use the following file as sample:

1. Read file

The paste command without any option is similar to "cat":

2. Join all lines into a single line

With the '-s' option, you can use paste to join all lines in a file:

3. Join all lines with a delimiter

With only the '-s' option, the default delimiter is a space to separate each part of the line. If you include the '-d' option, you can set a delimiter for the new line. For example, if you want the delimiter to be a hyphen:
 paste -d- -s file  

Or if you want the delimiter to be a comma:
 paste -d, -s file  

4. Merge the file into multiple columns

If you want to merge the file into 2 columns, the command will be:
 paste - - < file  

Similarly, to get 3 columns, you need one more hyphen:
 paste - - - < file  

5. Merge the file into multiple columns with delimiters

Here we use the '-d' option again. This '-d' option can be used for multiple delimiters as well. For example:
 paste -d':' - - < file  

 paste -d':*' - - - < file  

Use paste with multiple files

The above examples are about how to use paste with a single file. Now we deal with multiple files. Let's use another sample file:

6. paste 2 files side by side

With no option, you can paste two files side by side like this
 paste file file2  

Use the '-d' option in case you need a delimiter
 paste -d- file file2  

7. paste 2 files alternatively line by line

Using the '-d' option with '\n', we will have an output of the combined content of 2 files line by line:
 paste -d'\n' file file2  

linux tips and tricks