Linux Bash:将字符串添加到文件末尾而不换行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8739427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash: add string to the end of the file without line break
提问by Crazy_Bash
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
采纳答案by Dimitre Radoulov
sed '$s/$/yourText2/' list.txt > _list.txt_ && mv -- _list.txt_ list.txt
If your sedimplementation supports the -ioption, 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
回答by Franz
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.
编辑:啊哈,你已经有一个包含字符串和换行符的文件。好吧,无论如何我都会把它留在这里,我们可能对某人有用。
回答by fedorqui 'SO stop harming'
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
回答by Will Charlton
The above answers didn't work for me. Posting a Python implementation in case anyone finds it useful.
以上答案对我不起作用。发布一个 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)"