1

When I run the following code

echo '1' > file.txt
echo '2' | paste file.txt - > file.txt

I would expect the content of file.txt be 1 2, because the paste command as it name suggests should put the two strings simply side-by-side. However, it is just 2.

Could anyone of you point me towards additional diagnostics to run in order to pin down the problem.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
  • Why would you use paste? Just `echo '2' >> file.txt`. Your issue is that you are using `>` rather than `>>`. – Questionmark Apr 20 '15 at 15:33
  • Thanks a lot for your comment. It was just a minimal example. Actually, I would like to paste multiline output to a multiline file. – Penguin Nurse Apr 21 '15 at 10:36

1 Answers1

3

The redirection to file.txt at the end of your paste command is truncating your file before paste has a chance to read it.

Try

echo 2 | paste file.txt - > file2.txt

or if you have sponge installed

echo 2 | paste file.txt - | sponge file.txt
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
  • Hi Stephen, thanks for your answer. Both solutions work. Solution 1 has the disadvantage of creating an additional file (maybe that's unavoidable). Solution 2 reduces portability, because it needs additional software to be installed. Your answer is still helpful, though. – Penguin Nurse Apr 21 '15 at 10:38