如果换行符是文件中的最后一个字符,如何删除换行符? [英] How can I delete a newline if it is the last character in a file?

查看:39
本文介绍了如果换行符是文件中的最后一个字符,如何删除换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文件,如果它是文件中的最后一个字符,我想删除最后一个换行符.od -c 向我显示我运行的命令确实在文件中添加了一个新行:

I have some files that I'd like to delete the last newline if it is the last character in a file. od -c shows me that the command I run does write the file with a trailing new line:

0013600   n   t  >  

我已经尝试了一些使用 sed 的技巧,但我能想到的最好的方法是没有做到这一点:

I've tried a few tricks with sed but the best I could think of isn't doing the trick:

sed -e '$s/(.*)
$/1/' abc

任何想法如何做到这一点?

Any ideas how to do this?

推荐答案

perl -pe 'chomp if eof' filename >filename2

或者,就地编辑文件:

perl -pi -e 'chomp if eof' filename

[编者注:-pi -e 最初是 -pie,但是,正如一些评论者所指出的和@hvd 所解释的,后者不是没有工作.]

在我看到的 awk 网站上,这被描述为对 perl 的亵渎".

This was described as a 'perl blasphemy' on the awk website I saw.

但是,在测试中,它奏效了.

But, in a test, it worked.

这篇关于如果换行符是文件中的最后一个字符,如何删除换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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