从一堆文件的末尾删除空白行

时间:2019-06-23 09:19:29

标签: bash perl awk sed grep

我有一堆文件,其中有很多行,最后通常是一两个空行。

我想最后删除空白行,同时保留文件中可能存在的所有空白行。

我想将操作限制为使用GNU实用工具或类似工具,例如bash,sed,awk,cut,grep等。

我知道我可以轻松删除 all 空白行,例如:

sed '/^$/d'

但是我想保留空白行,该行在文件中的其他内容之前存在。

文件输入可能如下:

line1
line2

line4
line5


我希望输出看起来像这样:

line1
line2

line4
line5

所有文件均为<100K,我们可以制作临时副本。

4 个答案:

答案 0 :(得分:3)

使用Perl:

perl -0777 -pe 's/\n*$//; s/$/\n/' file

第二个S命令(s/$/\n/)再次在文件末尾添加一个换行符,以便可以进行POSIX编译。

或更短:

perl -0777 -pe 's/\n*$/\n/' file

使用Fela Maslen的注释来编辑文件(-i),并遍历当前目录中的所有元素(*):

perl -0777 -pe 's/\n*$/\n/' -i *

答案 1 :(得分:2)

这是一个awk解决方案(标准linux gawk)。我喜欢写作。

单行:

awk '/^\s*$/{s=s $0 ORS; next}{print s $0; s=""}' input.txt

使用可读的脚本script.awk

    /^\s*$/{skippedLines = skippedLines $0 ORS; next}
    {print skippedLines $0; skippedLines= ""}

说明:

/^\s*$/ {                   # for each empty line
    skippedLines = skippedLines $0 ORS; # pad string of newlines
    next;                   # skip to next input line
}
{                           # for each non empty line
    print skippedLines $0;  # print any skippedLines and current input line
    skippedLines= "";       # reset skippedLines
}

答案 2 :(得分:2)

如果仅包含空格字符的行被认为是空的:

$ tac file | awk 'NF{f=1}f' | tac
line1
line2

line4
line5

否则:

$ tac file | awk '/./{f=1}f' | tac
line1
line2

line4
line5

答案 3 :(得分:1)

这可能对您有用(GNU sed):

sed ':a;/\S/{n;ba};$d;N;ba' file

如果当前行包含非空格字符,请打印当前图案空间,获取下一行并重复。如果当前行为空并且是文件中的最后一行,则删除模式空间,否则追加下一行并重复。