3

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

G

O TO P999-ERREUR

END-IF.

the pattern in this case is G I want to have this output

 G
 O TO P999-ERREUR

 END-IF.
1
  • better edit to show your attempts and format properly Commented Aug 12, 2015 at 10:03

4 Answers 4

9

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
Sign up to request clarification or add additional context in comments.

Comments

6

Using 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.


Note this will only remove one blank line after, and the line must be blank i.e not spaces or tabs.

Comments

1

This might work for you (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.

Comments

1

Using ex (edit in-place):

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
  • %p - prints the buffer
  • q! - quits

For conditional checking (if there is a blank line), try:

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

1 Comment

You can replace foo.txt with /dev/stdin. However it doesn't check for the blank line, let me check that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.