与sed,awk,tr和朋友删除尾随/开始的换行符 [英] Removing trailing / starting newlines with sed, awk, tr, and friends

查看:83
本文介绍了与sed,awk,tr和朋友删除尾随/开始的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件中删除所有空行,但是仅当它们在文件的末尾/开始时才删除(也就是说,如果在它们之前没有非空行,则在开始处;以及如果在它们之后没有非空行,那么最后.)

I would like to remove all of the empty lines from a file, but only when they are at the end/start of a file (that is, if there are no non-empty lines before them, at the start; and if there are no non-empty lines after them, at the end.)

在诸如Perl或Ruby之类的功能齐全的脚本语言之外,这是否可能?如果可能,我希望使用sedawk进行此操作.基本上,任何轻量级且广泛可用的UNIX-y工具都可以,特别是我可以快速了解更多的工具(因此,不包括Perl.)

Is this possible outside of a fully-featured scripting language like Perl or Ruby? I’d prefer to do this with sed or awk if possible. Basically, any light-weight and widely available UNIX-y tool would be fine, especially one I can learn more about quickly (Perl, thus, not included.)

推荐答案

来自 用于sed的单行脚本 :

From Useful one-line scripts for sed:

# Delete all leading blank lines at top of file (only).
sed '/./,$!d' file

# Delete all trailing blank lines at end of file (only).
sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba' file

因此,要从文件中删除开头和结尾的空白行,可以将以上命令合并为:

Therefore, to remove both leading and trailing blank lines from a file, you can combine the above commands into:

sed -e :a -e '/./,$!d;/^\n*$/{$d;N;};/\n$/ba' file

这篇关于与sed,awk,tr和朋友删除尾随/开始的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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