加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-13 19:39:03 所属栏目:Linux 来源:网络整理
导读:echo -n 'I hate cats' cats.txtsed -i '' 's/hate/love/' cats.txt 这可以正确更改文件中的单词,但也会在文件末尾添加一个换行符.为什么?这只发生在OSX,而??不是Ubuntu等等.我该如何阻止它? 解决方法 echo -n 'I hate cats' cats.txt 此命令将使用单引号
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读