5

When i try to append to the end of a file it creates a new line. Now I have tried to fix this with echo -n but that doenst work.

So what am I trying. I'm trying to get the following result:

Hello
This
Is
A
Test

But when I Append text with echo with

echo -n "Test2" >> file.txt

The following thing happens:

Hello
This
Is
A
Test
Test2

But what I want is:

Hello
This
Is
A
Test Test2

How am I able to do this? I have tried sed,echo and printf but none of these give the right result

0

1 Answer 1

6

With sed:

sed '$s/$/ Test2/' file

or

truncate -s-1 file
echo -n " Test2" >> file

Output:

Hello
This
Is
A
Test Test2
8
  • Thank you, the sed option works, except it shows the output in the console. It doenst place it the text in the file. Is that normal?
    – Kev30
    Commented Jun 20, 2018 at 18:59
  • If you want to edit your file "in place" with GNU sed add option -i: sed -i '$s/$/ Test2/' file
    – Cyrus
    Commented Jun 20, 2018 at 19:01
  • I have added sed -i '$s/$/ Test2/' tmp.txt but now I am ending up with an empty file
    – Kev30
    Commented Jun 20, 2018 at 19:03
  • Do you use GNU sed?
    – Cyrus
    Commented Jun 20, 2018 at 19:07
  • 1
    you have an empty file because you probably did this at one point: sed '...' tmp.txt > tmp.txt -- if you do this, the shell will truncate the file before launching sed. Commented Jun 20, 2018 at 19:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .