shelltextfile-manipulation

Convert vertical text into horizontal in shell


I just pondered upon this problem while executing some tasks in shell.

How can I convert a .txt file which contains text in the following format[vertical direction]:

H
e
l
l
o

W
o
r
l
d

Note: The line without any letter contains a space and EOL

I need to convert to:

Hello World

I tried the following command: cat file1.txt |tr '\n' ' ' >file2.txt

Output:

H e l l o  W o r l d

How can I proceed further? Sorry, if this question has already appeared. If so, please provide me the link to the solution or any command for the work around.


Solution

  • You are replacing the new lines with spaces. Instead, remove them with -d:

    $ echo "H
    > e
    >                   # <- there is a space here
    > W
    > o" | tr -d '\n'
    He Wo
    

    With a file:

    tr -d '\n' < file   # there is no need to `cat`!
    

    Problem here is that the last new line is removed, so the result is POSIXly a 0-lines file.