4

I've been reading about https://stackoverflow.com/questions/39791042/convert-vertical-text-into-horizontal-in-shell and wondering if tr alone can be used to convert vertical text to horizontal.

user@linux:~$ seq 3
1
2
3
user@linux:~$ 

I've tried the following solution, it works but not perfect.

user@linux:~$ seq 3 | tr -d '\n'
123user@linux:~$ 
user@linux:~$ 

Would it be possible to used tr alone to produce output like this?

Desired Output

user@linux:~$ seq 3 | tr command here
123
user@linux:~$ 
2
  • 1
    tr -d '\n' is finr for all piped and file-to-file operations. Don't be fooled by the tty output.
    – FelixJN
    May 31, 2019 at 12:28
  • 1
    @Fiximan no it's not. Otherwise the following would work as expected: seq 3 | tr -d '\n' | cat. Notice the pipe to cat here, which didn't add the newline as the OP wanted (and which POSIX text files are required to have).
    – Ruslan
    May 31, 2019 at 20:58

6 Answers 6

8

Choose whatever works for you.

$ seq 3 | paste -s -d ''
123
$ seq 3 | tr -d '\n';echo
123
$ seq 3 | awk 1 ORS='';echo
123
1
  • Note that paste -s -d '' is not portable nor POSIX. The portable equivalent would be paste -sd '\0' - Jun 1, 2019 at 10:55
4
$ seq -s '' 3
123

This instructs seq to use the empty string as separator for the numbers (rather than the default newline character).

2
  • Nice. Didn't know about this. What if the vertical text is saved in a file instead of seq 3?
    – user264359
    May 31, 2019 at 12:54
  • @Sabrina Then you would use any of the alternatives in asktyagi's answer.
    – Kusalananda
    May 31, 2019 at 13:03
2

Try this,

 seq 3 | paste -s -d ''
 123
  • -d, delimiters as null
  • -s, print in serial instead of in parallel
2
  • So it's not possible to use tr alone to solve this?
    – user264359
    May 31, 2019 at 12:09
  • Note that paste -s -d '' is not portable nor POSIX. The portable equivalent would be paste -sd '\0' - Jun 1, 2019 at 10:55
2

You could use two tr commands and some shell features (a shell built-in, and a here-string or here-doc):

seq 3 | (tr -d '\n'; tr -s '\n' <<< "")

seq 3 | (tr -d '\n'; tr -s '\n' << EOF

EOF
)
2
  • You might as well use tr -s '\n' <<< '' or tr x y <<< '' Jun 1, 2019 at 10:58
  • Good point, Stéphane; I got stuck initially trying to convert /dev/null or /dev/zero; I'll simplify it with your suggestion. Thank you!
    – Jeff Schaller
    Jun 1, 2019 at 11:02
1

A solution could be

echo $(seq 3 | tr -d '\n')

As you are removing all newlines with switch -d '\n' you have to add the last one again with some sort of trick.

0

Tried with below 2 methods

First method

command:

seq 3| perl -pne "s/\n//g"

output 123

Second(Python)

!/usr/bin/python

import re
z=[]
import subprocess
k=open('o','r')
for i in k:
    z.append(i.strip())

print "".join(z)

Note: Here o is the filename

output

@host-1-49 ~]# python o.py 
123

You must log in to answer this question.