bash sed 命令将文本行添加到文件的最后
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29956755/
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
Sed command to add line of text to the very end of a file
提问by Technic1an
I want to use sed to add a line of text to the very end of a file. In this case I am working on OS X and I want to add a line in the /etc/sudoers files. I want my string to be the last string in the file on its own line. Any ideas?
我想使用 sed 在文件的最后添加一行文本。在这种情况下,我在 OS X 上工作,我想在 /etc/sudoers 文件中添加一行。我希望我的字符串成为文件中单独一行的最后一个字符串。有任何想法吗?
Example:
例子:
text
text
text
<my string>
Thanks.
谢谢。
回答by Eric Renouf
If you can do it without sed it would be easy enough to do echo <line> >> /etc/sudoers
(though be careful that you have a valid line!).
如果你不用 sed 就可以做到,那将很容易做到echo <line> >> /etc/sudoers
(但要注意你有一个有效的行!)。
If you want do it with sed you could do sed -i -e '$a<line>' /etc/sudoers
to go to the last line then append your text.
如果你想用 sed 来做sed -i -e '$a<line>' /etc/sudoers
,你可以转到最后一行,然后附加你的文本。
回答by ctt
Consider using echo
and output redirection:
考虑使用echo
和输出重定向:
sudo sh -c "echo 'my string' >> /etc/sudoers"
.
.
回答by Jotne
You can use awk
您可以使用 awk
awk '1; END {print "text to add"}' file > tmp && mv tmp file
This will add text to add
as a new line at the end of file file
这将text to add
在文件末尾添加一个新行file
回答by Saumyadip Pramanik
I have also tried to achieve this using sed, but unfortunately, haven't found any solution yet. But I have found a workaround to achieve this using echo:
我也尝试过使用 sed 来实现这一点,但不幸的是,还没有找到任何解决方案。但是我找到了一种解决方法来使用 echo 实现这一点:
$ echo "the line you want to add" >> yourTextFile.txt
$ echo "您要添加的行" >> yourTextFile.txt