简体   繁体   English

仅在使用sed或awk将其为空白的情况下删除模式之后的行

[英]delete a line after a pattern only if it is blank using sed or awk

I want to delete a blank line only if this one is after the line of my pattern using sed or awk for example if I have 我只想删除空白行,例如,如果此行在使用sed或awk的模式行之后,例如

G

O TO P999-ERREUR

END-IF.

the pattern in this case is G I want to have this output 在这种情况下的模式是G我想要这个输出

 G
 O TO P999-ERREUR

 END-IF.

This will do the trick: 这将达到目的:

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

END-IF.

Explanation: 说明:

-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

Using sed 使用sed

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

If it sees GG, gets the next line, removes the newline between them if the next line is empty. 如果看到GG,则获取下一行,如果下一行为空,则删除它们之间的换行符。


Note this will only remove one blank line after, and the line must be blank ie not spaces or tabs. 请注意,这只会在之后删除一个空白行,并且该行必须为空白,即不能为空格或制表符。

Using ex (edit in-place): 使用ex (就地编辑):

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

or print to the standard output (from file or stdin): 或打印到标准输出(从文件或标准输入):

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

where: 哪里:

  • /GG/j - joins the next line when the pattern is found /GG/j找到模式后加入下一行
  • %p - prints the buffer %p打印缓冲区
  • q! - quits -退出

For conditional checking (if there is a blank line), try: 对于条件检查(如果有空白行),请尝试:

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

This might work for you (GNU sed): 这可能对您有用(GNU sed):

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

Keep a moving window of two lines throughout the length of the file and remove a newline (and any whitespace) if it follows the intended pattern. 在文件的整个长度上保持两行移动的窗口,如果换行符符合预期的模式,则删除换行符(和所有空格)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM