简体   繁体   English

为什么 sed 向文件添加新行以及如何防止它?

[英]Why is sed adding a new line to the file and how to prevent it?

How can I prevent sed from adding a new line at the end of the file using this command:如何使用以下命令防止 sed 在文件末尾添加新行:

find . -not -path "./.git/*" -type f -name '*' -exec sed -i '' 's/password1/passworddeleted/g; s/password2/passworddeleted/g;' {} +

EDIT: To prove my question:编辑:为了证明我的问题:

mkdir test; cd test; printf "no new lines" > no-new-line.txt; cat -e no-new-line.txt; find . -not -path "./.git/*" -type f -name '*' -exec sed -i '' 's/password1/passworddeleted/g; s/password2/passworddeleted/g;' {} +; cat -e no-new-line.txt;

Will output no new linesno new lines$ .将输出no new linesno new lines$ cat -e displays non-printing characters on mac. cat -e在 mac 上显示非打印字符。

sed always ends its output by a newline character and you cannot force it to do otherwise. sed总是以换行符结束它的输出,你不能强迫它这样做。

From POSIX man sed :来自POSIX man sed

Whenever the pattern space is written to standard output or a named file, sed shall immediately follow it with a newline.每当模式空间被写入标准输出或命名文件时,sed 应立即在其后面添加一个换行符。

As an alternative, you can use something else than sed or strip the last character of sed 's output.作为替代方案,您可以使用sed以外的其他内容或sed输出的最后一个字符。

You can use this, or combine with pipe:您可以使用它,或与管道结合使用:

truncate -s -1 <file>

(this remove the last byte of the file ) (这将删除文件的最后一个字节)

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

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