Search code examples
bashmacosshellterminalzsh

Join all lines of stream


How can I join all the lines?

Desired output:

$ echo 'one\ntwo' | tr '\n' ''
onetwo

Actual output:

tr: empty string2

I have also tried paste -sd '' - but get

paste: no delimiters specified

also sed

$ echo 'one\ntwo' | sed 's/\n//'
one
two

Solution

  • tr requires that the second argument have at least one character, so it knows what to translate the characters in the first argument to. If there are less characters in the replacement string than in the match string, the last character of the replacement is used for all the rest. But if the replacement is empty, there's nothing to repeat for the rest.

    If you want to delete characters, use tr -d.

    echo $'one\ntwo' | tr -d '\n' 
    

    Note also that you have to use $'...' to get bash to treat \n as a newline. Otherwise it's the literal string \n.