仅当它不存在时才添加换行符 [英] Add a newline only if it doesn't exist

查看:18
本文介绍了仅当它不存在时才添加换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当文件不存在时,我才想在文件末尾添加换行符.这是为了防止文件末尾出现多个换行符.

I want to add a newline at the end of a file only if it doesn't exist. This is to prevent multiple newlines at the end of the file.

我希望使用 sed.以下是我当前代码的问题:

I'm hoping to use sed. Here are 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 doesn't have one but removes it 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆