简体   繁体   English

使用 sed 在文件末尾添加新行

[英]Adding a new line to the end of a file using sed

I need to add a new line to the end of a file.我需要在文件末尾添加一个新行。 But when I am running sed command on MacOS I get an error.但是当我在 MacOS 上运行 sed 命令时出现错误。

The command I run sed -i'' -e '$a\wrapper{gradleVersion='5.5'}' build.gradle我运行的命令sed -i'' -e '$a\wrapper{gradleVersion='5.5'}' build.gradle

The error I get: sed: 1: "$a\wrapper{gradleVersio...": extra characters after \ at the end of a command我得到的错误: sed: 1: "$a\wrapper{gradleVersio...": extra characters after \ at the end of a command

Simplest answer: do not use sed最简单的答案:不要使用sed

echo "wrapper{gradleVersion='5.5'}" >> build.gradle

Pretty straightforward right?很简单吧?

If you want to ignore my advices and keep using sed , to complete @shellter comment:如果您想忽略我的建议并继续使用sed ,请完成@shellter 评论:

  • On MacOS sed, you need to add newlines before the text you want to add when using a command.在 MacOS sed 上,您需要在a命令时在要添加的文本之前添加换行符。

  • MacOS sed will not add a newline by default after the text you want to add, and because you want the file remains POSIX standard, you'll need to add it MacOS sed 默认情况下不会在您要添加的文本后添加换行符,并且因为您希望文件保持 POSIX 标准,所以您需要添加它

You can do:你可以做:

sed -i '' -e '$a\
<text to add>
' <file>
  • Because you want to add single quotes, you need to wrap sed command with double quotes, then escape $ and \ which make it particularly annoying to use.因为要添加单引号,所以需要将 sed 命令用双引号括起来,然后转义$\ ,这样使用起来特别烦人。

Try this:尝试这个:

sed -i '' "\$a\\
wrapper{gradleVersion='5.5'}
" build.gradle

On gnu-sed (install it with brew brew install gnu-sed ), you would do:在 gnu-sed 上(使用brew brew install gnu-sed ),您可以:

gsed -i "\$a wrapper{gradleVersion='5.5'}" build.gradle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM