How to line wrap output in bash?

2019-08-03 19:05发布

问题:

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. (Line wrapped)

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

回答1:

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 $


回答2:

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.



回答3:

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.



回答4:

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.



标签: bash shell