Reputation: 1076
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.
Upvotes: 2
Views: 16730
Reputation: 1076
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
Upvotes: 0
Reputation: 17721
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
Upvotes: 2
Reputation: 290155
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.
Upvotes: 5
Reputation: 18401
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
Upvotes: 1