Francesco Marchioni
Francesco Marchioni

Reputation: 4328

Remove empty lines followed by a pattern


I'm trying to find a way to remove empty lines which are found in my asciidoc file before a marker string, such as:

//Empty line
[source,shell]

I'd need:

[source,shell]

I'm trying with:

sed '/^\s*$\n[source,shell]/d' file

however it doesn't produce the expected effect (even escaping the parenthesis). Any help ?

Upvotes: 1

Views: 328

Answers (2)

GarryM
GarryM

Reputation: 527

You may use this awk-script to delete previous empty line:

awk -v desired_val="[source,shell]" 
'BEGIN { first_time=1 }
 { 
   if ( $0 != desired_val && first_time != 1) { print prev };
   prev = $0;
   first_time = 0;
 }
 END { print $0 }' your_file

Next script is little more than previous, but provides deleting all empty lines before desired value.

# AWK script file
# Provides clearing all empty lines in front of desired value 
# Usage: awk -v DESIRED_VAL="your_value" -f "awk_script_fname" input_fname

BEGIN { i=0 }
{ 
  # If line is empty - save counts of empty strings
  if ( length($0) == 0 ) { i++; }

  # If line is not empty and is DESIRED_VAL, print it  
  if ( length ($0) != 0 && $0 == DESIRED_VAL )
  {
    print $0; i=0;
  }

  # If line is not empty and not DESIRED_VAL, print all empty str and current
  if ( length ($0) != 0 && $0 != DESIRED_VAL )
  {   
    for (m=0;m<i;m++) { print ""; } i=0; print $0;
  }
}

# If last lines is empty, print it
END { for (m=0;m<i;m++) { print ""; } }

This is awk-script used by typing followed command:

awk -v DESIRED_VAL="your_value" -f "awk_script_fname" input_fname

Upvotes: 2

Sir Athos
Sir Athos

Reputation: 9867

Your sed line doesn't work because sed processes one line at a time, so it will not match a pattern that includes \n unless you manipulate the pattern space.

If you still want to do it with sed:

sed '/^$/{N;s/\n\(\[source,shell]\)/\1/}' file

How it works: When matching an empty line, read the next line into the pattern space and remove the empty line if a marker is found. Note that this won't work correctly if you have two empty lines before the marker, as the first empty line will consume the second one and there will be no matching with the marker.

Upvotes: 0

Related Questions