How can I print multiline output on the same line?

70,248

Solution 1

You can remove all occurrences of characters from a given set with tr -d. To remove the newline character use:

tr -d '\n'

As always you can use input and output redirection and pipes to read from or write to files and other processes.

If you want to keep the last newline you can simply add it back with echo or printf '\n', e. g.:

cat file1 file2... | { tr -d '\n'; echo; } > output.txt

Solution 2

Many ways. To illustrate, I have saved your example in file:

$ cat file | tr -d '\n'
abcdefqwerty$ 
$ cat file | perl -pe 's/\n//'
abcdefqwerty$ 

That removes all newline characters, including the last one though. You might instead want to do:

$ printf "%s\n" "$(cat file | perl -pe 's/\n//')"
abcdefqwerty
$ printf "%s\n" "$(cat file | tr -d '\n')"
abcdefqwerty

Solution 3

You can pipe your multiline output through awk

awk '{printf "%s",$0} END {print ""}'

or use sed:

sed ':a;N;$!ba;s/\n//g'

Example run

$ echo -e "1\n2\n3\n4" | awk '{printf "%s",$0} END {print ""}'
1234
$ echo -e "1\n2\n3\n4" | sed ':a;N;$!ba;s/\n//g'              
1234

Further reading: remove line break using AWK · serverfault.SE

Solution 4

Also your_command | paste -sd '' which preserves the trailing newline.

Solution 5

This answer has a solution to the problem you are trying to create: Why does bash remove \n in $(cat file)?

If you type cat myfile.txt you will see:

abc
def
ghi

But if you type echo $(cat myfile.txt) you will see:

abc def ghi

Note this method inserts a space where separate new lines used to be. This makes the output easier to read but doesn't strictly adhere to your question scope.

Share:
70,248

Related videos on Youtube

Shrinidhi Kulkarni
Author by

Shrinidhi Kulkarni

A 24 year old devops engineer who loves tech,bash and systems. https://shrinidhi.surge.sh/

Updated on September 18, 2022

Comments

  • Shrinidhi Kulkarni
    Shrinidhi Kulkarni over 1 year

    Is there a method to print multi-line output (single output) on the same line?

    For example, if the output is:

    abc
    def
    qwerty
    

    Is it possible to print:

    abcdefqwerty 
    
  • Sergiy Kolodyazhnyy
    Sergiy Kolodyazhnyy about 6 years
    perl -wpe 'chomp; END { print "\n" } is same process, minor advantage over adding trailing echo
  • Sergiy Kolodyazhnyy
    Sergiy Kolodyazhnyy almost 6 years
    I think the printf + cat + perl combo is much better handled via perl -pe 's/\n//;END{printf "\n"}' input.txt Single process, no command-substitution and messing with quotes, and no UUOC. Perhaps.
  • element11
    element11 over 3 years
    For those that want to keep a space between each line, you can use tr '\n' ' '