Skip to content
Advertisement

Bash: add string to the end of the file without line break

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

Advertisement

Answer

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
Advertisement