【问题标题】:delete a line after a pattern only if it is blank using sed or awk仅当使用 sed 或 awk 为空白时,才删除模式后的一行
【发布时间】:2015-08-12 10:02:08
【问题描述】:

我只想删除一个空行,前提是该空行位于我使用 sed 或 awk 的模式行之后 例如,如果我有

G

O TO P999-ERREUR

END-IF.

这种情况下的模式是G 我想要这个输出

 G
 O TO P999-ERREUR

 END-IF.

【问题讨论】:

  • 更好的edit 来展示你的尝试和正确的格式

标签: linux bash awk sed


【解决方案1】:

这样就可以了:

$ awk -v n=-2 'NR==n+1 && !NF{next} /G/ {n=NR}1' file
G
O TO P999-ERREUR

END-IF.

解释:

-v n=-2    # Set n=-2 before the script is run to avoid not printing the first line
NR == n+1  # If the current line number is equal to the matching line + 1
&& !NF     # And the line is empty 
{next}     # Skip the line (don't print it)
/G/        # The regular expression to match
{n = NR}   # Save the current line number in the variable n
1          # Truthy value used a shorthand to print every (non skipped) line

【讨论】:

    【解决方案2】:

    使用 sed

    sed '/GG/{N;s/\n$//}' file
    

    如果它看到 GG,则获取下一行,如果下一行为空,则删除它们之间的换行符。


    请注意,这只会删除一个空行,并且该行必须是空白的,即不能是空格或制表符。

    【讨论】:

      【解决方案3】:

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

      sed -r 'N;s/(G.*)\n\s*$/\1/;P;D' file
      

      在整个文件的长度上保留一个两行的移动窗口,如果它遵循预期的模式,则删除一个换行符(和任何空格)。

      【讨论】:

        【解决方案4】:

        使用ex(就地编辑):

        ex +'/G/j' -cwq foo.txt 
        

        或打印到标准输出(从文件或标准输入):

        ex -s +'/GG/j|%p|q!' file_or_/dev/stdin
        

        地点:

        • /GG/j - 找到模式后加入下一行
        • %p - 打印缓冲区
        • q! - 退出

        对于条件检查(如果有空行),尝试:

        ex -s +'%s/^\(G\)\n/\1/' +'%p|q!' file_or_/dev/stdin
        

        【讨论】:

        • 您可以将foo.txt 替换为/dev/stdin。但是它不检查空行,让我检查一下。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-31
        相关资源
        最近更新 更多