В bash, как объединить вывод двух команд и добавить их в одну и ту же строку файла?

2882
Galaxy

Например, у меня есть две команды здесь:

{ command1 & command2; } >> file1 

Например, вывод command1is 400, а вывод command2is 4.

Так вот что я получаю:

400 4 

Я хочу, чтобы результаты двух команд добавлялись в одну строку следующим образом:

400 4 
0
Вы уверены, что получите этот результат? Вы помещаете command1 в фоновый режим, так как вы знаете, что вы гарантированно получите его вывод первым? glenn jackman 8 лет назад 0

2 ответа на вопрос

1
Zoredache

Your command basically is this.

$ (echo '400' && echo '4') | hexdump -C 00000000 34 30 30 0a 34 0a |400.4.| 00000006 

Not the output includes the end of line \n aka 0a characters. So one easy thing you could do is pipe that through a command that will delete the \n.

So something like this

$ (echo '400' && echo '4') | tr '\n' ' ' | hexdump -C 00000000 34 30 30 20 34 20 |400 4 | 00000006 

Which has actual output of 400 4. But that doesn't include any line endings so you may want to only remove the line ending from the first command.

$ (echo '400' | tr '\n' ' ' && echo '4') | hexdump -C 00000000 34 30 30 20 34 0a |400 4.| 00000006 

Anyway, the point is that the line ending is just a character use tr, sed, awk, or your favorite tool that lets you do manipulation of the string.

One other option that may work, depending on your requirements may be to do something like below. With this, the output of the commands are magically stripped of the EOL for you, but an EOL is appended by the echo command.

$ echo "$(echo '400') $(echo '4')" | hexdump -C 00000000 34 30 30 20 34 0a |400 4.| 00000006 
Я не хочу отображать "400". 400 - это просто заполнитель для вывода команды. Galaxy 8 лет назад 0
Я знаю, замените 'echo 400' своей командой. Я использовал это в качестве примера. Echo была просто полезной ** командой **, которая позволяла мне быстро создавать примеры, которые давали результаты, которые точно соответствовали тому, что вы имели в своем вопросе. Zoredache 8 лет назад 1
Также есть: `paste <(cmd1) <(cmd2) >> file.txt` Seb B. 8 лет назад 0
1
glenn jackman

I'd use paste

{ command1 & command2; } | paste -d" " -s >> file1 

(concern about backgrounding command1 has been noted)

Demo:

$ { echo 400; echo 4; } 400 4 $ { echo 400; echo 4; } | paste -d" " -s 400 4 

Похожие вопросы