26

How can I add string to the end of the file without line break?

for example if i'm using >> it will add to the end of the file with line break:

cat list.txt
yourText1
root@host-37:/# echo yourText2 >> list.txt
root@host-37:/# cat list.txt
yourText1
yourText2

I would like to add yourText2 right after yourText1

root@host-37:/# cat list.txt
yourText1yourText2
Crazy_Bash
  • 1,755
  • 10
  • 26
  • 38
  • echo -n seems to be the command you look for. – stephanmg Oct 04 '19 at 12:04
  • here may be [the answer you want](https://unix.stackexchange.com/questions/412835/append-text-with-echo-without-new-line); Note that if you also want to use a variable in sed comman, variable in single quote would not get expended, use double quote instead. – GG.Fan Jun 27 '22 at 08:09

4 Answers4

74

You can use the -n parameter of echo. Like this:

$ touch a.txt
$ echo -n "A" >> a.txt
$ echo -n "B" >> a.txt
$ echo -n "C" >> a.txt
$ cat a.txt
ABC

EDIT: Aha, you already had a file containing string and newline. Well, I'll leave this here anyway, might we useful for someone.

Franz
  • 1,993
  • 13
  • 20
  • very proper, sir that is how I would carry it out. plus if you're not starting with a file then `>>` will touch it with any extenion you give or none at all, for example one my favorite lines of code: `$ cat ~/.ssh/id_rsa.pub | ssh itsme@nopasswordcheckneeded.com 'cat >> ~/.ssh/authorized_keys'` then the next line is `$ ssh-add -K` and walla! no more password prompt every time I need to remote onto that machine – Bent Cardan Jul 05 '13 at 20:35
13

Just use printf instead, since it does not print the new line as default:

printf "final line" >> file

Test

Let's create a file and then add an extra line without a trailing new line. Note I use cat -vet to see the new lines.

$ seq 2 > file
$ cat -vet file
1$
2$
$ printf "the end" >> file
$ cat -vet file
1$
2$
the end
fedorqui
  • 275,237
  • 103
  • 548
  • 598
6
sed '$s/$/yourText2/' list.txt > _list.txt_ && mv -- _list.txt_ list.txt

If your sed implementation supports the -i option, you could use:

sed -i.bck '$s/$/yourText2/' list.txt

With the second solution you'll have a backup too (with first you'll need to do it manually).

Alternatively:

ex -sc 's/$/yourText2/|w|q' list.txt 

or

perl -i.bck -pe's/$/yourText2/ if eof' list.txt
Dimitre Radoulov
  • 27,252
  • 4
  • 40
  • 48
0

The above answers didn't work for me. Posting a Python implementation in case anyone finds it useful.

python -c "txtfile = '/my/file.txt' ; f = open(txtfile, 'r') ; d = f.read().strip() ; f.close() ; d = d + 'the data to append' ; open(txtfile, 'w').write(d)"
Will Charlton
  • 862
  • 10
  • 11