仅在不存在换行符时添加它 [英] Add a newline only if it doesn't exist
本文介绍了仅在不存在换行符时添加它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想在文件末尾添加换行符,以防止在文件末尾添加多个换行符.
I want to add a newline at the end of a file only if it doesn't exists, this is to prevent multiple newlines at the end of the file.
我希望使用sed. 这是我当前代码遇到的问题:
I'm hoping to use sed. Here's the issues i'm having with my current code:
sed -i -e '/^$/d;$G' /inputfile
echo file1
name1
name2
echo file2
name3
name4
(newline)
当我在文件上运行代码时
when i run my code on to the files;
echo file1
name1
name2
(newline)
echo file2
name3
name4
如果没有则添加一个换行符,但是如果存在则删除一个...这使我感到困惑.
it adds a newline if it doesnt have but removes if it exists... this puzzles me..
推荐答案
由于如果不存在换行符,它将删除换行符,因此您可以简单地使用:
Since it removes newline if it's not there, you could simply use:
echo "" >> file; sed -ie '/^$/d;$G' file; sed -ie '/^$/d;$G' file
添加换行符并删除所有内容,然后添加换行符.不是优雅的方式,但肯定可以:)
Adds a newline and removes everything then adds newline. Not the elegant way, but certainly works :)
这篇关于仅在不存在换行符时添加它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文