为什么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

相关文章

insmod和modprobe加-f参数导致Invalid module format错误 这...
将ArchLinux安装到U盘 几个月前入门Arch的时候上网搜了不少安...
1、安装Apache。 1)执行如下命令,安装Apache服务及其扩展包...
一、先说一下用ansible批量采集机器信息的实现办法: 1、先把...
安装配置 1. 安装vsftpd 检查是否安装了vsftpd # rpm -qa | ...
如何抑制stable_secret读取关键的“net.ipv6.conf.all.stabl...