只有在使用sed或awk为空时才删除模式后面的一行

mal*_*lmo 0 linux bash awk sed

我想删除一个空白行,只有当这个使用sed或awk时我的模式行之后,例如我有

G

O TO P999-ERREUR

END-IF.
Run Code Online (Sandbox Code Playgroud)

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

 G
 O TO P999-ERREUR

 END-IF.
Run Code Online (Sandbox Code Playgroud)

Chr*_*our 8

这样就可以了:

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

END-IF.
Run Code Online (Sandbox Code Playgroud)

说明:

-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
Run Code Online (Sandbox Code Playgroud)


123*_*123 5

使用 sed

sed '/GG/{N;s/\n$//}' file
Run Code Online (Sandbox Code Playgroud)

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


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