Bash:在没有换行的情况下将字符串添加到文件末尾

问题描述 投票:20回答:4

如何在没有换行符的情况下将字符串添加到文件末尾?

例如,如果我使用>>它将添加到文件的末尾与换行符:

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

我想在yourText1之后添加yourText2

root@host-37:/# cat list.txt
yourText1yourText2
linux bash awk echo cat
4个回答
6
投票
sed '$s/$/yourText2/' list.txt > _list.txt_ && mv -- _list.txt_ list.txt

如果您的sed实现支持-i选项,您可以使用:

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

使用第二种解决方案,您也将获得备份(首先您需要手动执行)。

或者:

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

要么

perl -i.bck -pe's/$/yourText2/ if eof' list.txt

53
投票

您可以使用echo的-n参数。像这样:

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

编辑:啊哈,你已经有一个包含字符串和换行符的文件。好吧,无论如何,我会留在这里,我们可能对某人有用。


9
投票

只需使用printf,因为它不会默认打印新行:

printf "final line" >> file

Test

让我们创建一个文件,然后添加一个没有尾随新行的额外行。注意我使用cat -vet来查看新行。

$ seq 2 > file
$ cat -vet file
1$
2$
$ printf "the end" >> file
$ cat -vet file
1$
2$
the end

0
投票

以上答案对我不起作用。发布Python实现,以防任何人发现它有用。

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)"
© www.soinside.com 2019 - 2024. All rights reserved.