user244333
user244333

Reputation:

How to join lines from output in bash?

I have a command which outputs in this format:

A
B
C
D
E
F
G
I
J

etc I want the output to be in this format

A B C D E F G I J

I tried using ./script | tr "\n" " " but all it does is remove n from the output How do I get all the output in one line.

Edit: I accidentally put in grep while asking the question. I removed it. My original question still stands.

Upvotes: 2

Views: 5129

Answers (4)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38042

If I'm not mistaken, the echo command will automatically remove the newline chars when its argument is given unquoted:

tmp=$(./script.sh)
echo $tmp

results in

A B C D E F G H I J

whereas

tmp=$(./script.sh)
echo "$tmp"

results in

A 
B 
C 
D 
E 
F 
G 
H 
I 
J

If needed, you can re-assign the output of the echo command to another variable:

tmp=$(./script.sh)
tmp2=$(echo $tmp)

The $tmp2 variable will then contain no newlines.

Upvotes: 0

cdarke
cdarke

Reputation: 44394

No need to use other programs, why not use Bash to do the job? (-- added in edit)

line=$(./script.sh) 
set -- $line
echo "$*"

The set sets command-line options, and one of the (by default) seperators is a "\n". EDIT: This will overwrite any existing command-line arguments, but good coding practice would suggest that you reassigned these to named variables early in the script.

When we use "$*" (note the quotes) it joins them alll together again using the first character of IFS as the glue. By default that is a space.

tr is an unnecessary child process.

By the way, there is a command called script, so be careful of using that name.

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263497

As Jonathan Leffler points out, you don't want the grep. The command you're using:

./script | grep tr "\n" " "

doesn't even invoke the tr command; it should search for the pattern "tr" in files named "\n" and " ". Since that's not the output you reported, I suspect you've mistyped the command you're using.

You can do this:

./script | tr '\n' ' '

but (a) it joins all its input into a single line, and (b) it doesn't append a newline to the end of the line. Typically that means your shell prompt will be printed at the end of the line of output.

If you want everything on one line, you can do this:

./script | tr '\n' ' ' ; echo ''

Or, if you want the output wrapped to a reasonable width:

./script | fmt

The fmt command has a number of options to control things like the maximum line length; read its documentation (man fmt or info fmt) for details.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 754500

The grep is superfluous.

This should work:

./script | tr '\n' ' '

It did for me with a command al that lists its arguments one per line:

$ al A B C D E F G H I J
A
B
C
D
E
F
G
H
I
J
$ al A B C D E F G H I J | tr '\n' ' '
A B C D E F G H I J $

Upvotes: 4

Related Questions