bash 将两个命令的输出连接到一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5448915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:20:29  来源:igfitidea点击:

Concatenate output of two commands into one line

bashshellconcatenation

提问by slhck

I have a very basic shell script here:

我这里有一个非常基本的 shell 脚本:

for file in Alt_moabit Book_arrival Door_flowers Leaving_laptop
do
    for qp in 10 12 15 19 22 25 32 39 45 60
    do
        for i in 0 1
        do
            echo "$file\t$qp\t$i" >> psnr.txt
            ./command > $file-$qp-psnr.txt 2>> psnr.txt
        done
    done
done

commandcalculates some PSNR values and writes a detailed summary to a file for each combination of file, qpand i. That's fine.

command一些计算PSNR值和写入的详细总结为的每个组合一个文件fileqpi。没关系。

The 2>>outputs one line of information that I really need. But when executed, I get:

2>>输出的一行信息,我真正需要的。但是当执行时,我得到:

Alt_moabit  10  0
total   47,8221 50,6329 50,1031
Alt_moabit  10  1
total   47,8408 49,9973 49,8197
Alt_moabit  12  0
total   47,0665 50,1457 49,6755
Alt_moabit  12  1
total   47,1193 49,4284 49,3476

What I want, however, is this:

然而,我想要的是:

Alt_moabit  10  0    total  47,8221 50,6329 50,1031
Alt_moabit  10  1    total  47,8408 49,9973 49,8197
Alt_moabit  12  0    total  47,0665 50,1457 49,6755
Alt_moabit  12  1    total  47,1193 49,4284 49,3476

How can I achieve that?

我怎样才能做到这一点?

(Please feel free to change the title if you think there's a more appropriate one)

(如果您认为有更合适的标题,请随时更改标题)

采纳答案by drysdam

The (GNU version of) echo utility has a -n option to omit the trailing newline. Use that on your first echo. You'll probably have to put some space after the first line or before the second for readability.

(GNU 版本的)echo 实用程序有一个 -n 选项来省略尾随的换行符。在您的第一个回声中使用它。为了便于阅读,您可能需要在第一行之后或第二行之前放置一些空格。

回答by Pascal MARTIN

You could pass the -noption to your first echocommand, so it doesn't output a newline.

您可以将该-n选项传递给您的第一个echo命令,因此它不会输出换行符。


As a quick demonstration, this :


作为一个快速演示,这个:

echo "test : " ; echo "blah"

will get you :

会让你:

test : 
blah

With a newline between the two outputs.

在两个输出之间换行。


While this, with a -nfor the first echo:


而这个,-n第一个echo

echo -n "test : " ; echo "blah"

will get you the following output :

将为您提供以下输出:

test : blah

Without any newline between the two output.

两个输出之间没有任何换行符。

回答by kurumi

You can use printfinstead of echo, which is better for portability reasons.

您可以使用printf代替echo出于可移植性的原因,这更好

回答by William Pursell

printf is the correct way to solve your problem (+1 kurumi), but for completeness, you can also do:

printf 是解决您的问题的正确方法(+1 kurumi),但为了完整起见,您还可以执行以下操作:

   echo "$file\t$qp\t$i $( ./command 2>&1 > $file-$qp-psnr.txt )" >> psnr.txt