微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么sed在OSX中添加新行?

echo -n 'I hate cats' > cats.txt
sed -i '' 's/hate/love/' cats.txt

这可以正确更改文件中的单词,但也会在文件末尾添加一个换行符.为什么?这只发生在OSX,而​​不是Ubuntu等等.我该如何阻止它?

解决方法

echo -n 'I hate cats' > cats.txt

此命令将使用单引号之间的11个字符填充“cats.txt”的内容.如果在这个阶段检查cats.txt的大小应该是11个字节.

sed -i '' 's/hate/love/' cats.txt

该命令将逐行读取cats.txt文件,并将其替换为每个行的第一个“hate”替换为“love”(如果此类实例存在)的文件.重要的是了解一条线是什么.从sed手册页:

normally,sed cyclically copies a line of input,not including its
 terminating newline character,into a pattern space,(unless there is
 something left after a ``D'' function),applies all of the commands
 with addresses that select that pattern space,copies the pattern
 space to the standard output,appending a newline,and deletes the
 pattern space.

注意附加换行符.在您的系统上,sed仍然将您的文件解释为包含一行,即使没有终止的换行符.所以输出将是11个字符,加上附加的换行符.在其他平台上,情况并非如此.有时sed会完全跳过一个文件的最后一行(有效地删除它),因为it is not really a line!但是在你的情况下,sed基本上是为你修复文件(作为一个没有行的文件,它的输入是sed).

在这里查看更多细节:Why should text files end with a newline?

看到这个问题可以解决你的问题:SED adds new line at the end

原文地址:https://www.jb51.cc/linux/393709.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐