Skip to content

How to Merge Multiple Lines into One on Linux

  • by
There're 4 lines in a file:
[root@localhost ~]$ cat -n temp.txt
     1  Database Administration.
     2  Web Development.
     3  IT Architecture Design.
     4  Project Management.
[root@localhost ~]$

My goal is to make them concatenate into one line only with proper white spaces between them.
Here are the methods that you can replace all new line characters with a white space.
  1. paste
  2. [root@localhost ~]$ paste -d ' ' -s temp.txt
    Database Administration. Web Development. IT Architecture Design. Project Management.
    [root@localhost ~]$

    Or with tab characters.
    [oracle@primary01 ~]$ paste -d 't' -s temp.txt
    Database Administration.        Web Development.        IT Architecture Design. Project Management.
    [oracle@primary01 ~]$

  3. tr
  4. [root@localhost ~]$ cat temp.txt | tr -s 'n' ' '
    Database Administration. Web Development. IT Architecture Design. Project Management. [root@localhost ~]$

    Or with tab characters.
    [root@localhost ~]$ cat temp.txt | tr -s 'n' 't'
    Database Administration.        Web Development.        IT Architecture Design. Project Management.       [root@localhost ~]$

    In the above, I replaced all new line characters with white spaces or tabs by tr, and squeeze repeated characters by adding an option -s.
Did you see there's a minor imperfection? You may refer to this post for details:

Further Reading -How to Resolve No Carriage Return at End of File on Linux

Leave a Reply

Your email address will not be published. Required fields are marked *