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

时间:2021-09-10 21:42:44

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

我想在yourText1之后添加yourText2

root@host-37:/# cat list.txt
yourText1yourText2

3 个解决方案

#1


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选项,您可以使用:

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

#2


45  

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

您可以使用echo的-n参数。喜欢这个:

$ 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.

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

#3


8  

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

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

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.

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

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

#1


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选项,您可以使用:

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

#2


45  

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

您可以使用echo的-n参数。喜欢这个:

$ 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.

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

#3


8  

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

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

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.

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

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