2

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.

Liju Thomas
  • 1,054
  • 5
  • 18
  • 25

4 Answers4

5

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • thanks for your reply :) How to do for more than one string? .. Like, in the answer you have used `Hello` but what about for the example that I have mention above?.. – Liju Thomas Sep 30 '16 at 12:16
  • @LijuThomas oh, I just put some characters to prevent this being too long. Updated with an example with a space. – fedorqui Sep 30 '16 at 12:19
2

You were quite close... :-)
tr command has option -d to remove charactar classes, instead of just replacing.
So:

cat file1.txt | tr -d '\n' > file2.txt

Will just do...

UPDATE: after OP comment, this is a version which preserves empty newlines:

cat file1.txt | perl -p -i -e 's/\n(.+)/$1/' > file2.txt
MarcoS
  • 17,323
  • 24
  • 96
  • 174
  • Thanks for the quick reply :).. I tried the command but the output which I got is `HelloWorld`. My desired output is `Hello World` Can this be achieved? – Liju Thomas Sep 30 '16 at 12:11
  • 1
    @LijuThomas: you're right, sorry... I did not think about empty lines... In an update to my answer I address this case, too... .-) – MarcoS Sep 30 '16 at 12:33
1

Sample data:

echo "$x"
H
e
l
l
o

W
o
r
l
d

Solution:

  echo "$x"  |sed 's/^$/bla/'|awk 'BEGIN{OFS="";ORS=" ";RS="bla"}{$1=$1}1'
  Hello World 
P....
  • 17,421
  • 2
  • 32
  • 52
0

After going through all the suggestions and little bit of research, I found a solution for this, wrote a script for the same:

#!/bin/bash
#Converting text to horizontal direction

IFS=''
while read line
do
   echo -n $line
done < $1 > $2           # $1 --> file1.txt contain vertical text as mentioned in the question
echo "$(cat $2)"

Command:

$./convert.sh file1.txt file2.txt

Output:

Hello World
Liju Thomas
  • 1,054
  • 5
  • 18
  • 25