-2

I am trying to delete all empty lines, including spaces or tabs, and the line right above the empty line.

I have successfully used grep to get the empty line and the line above it, using grep -B 1 -e '^[[:space:]]*$' filename . I have tried adding the -v flag to remove the match from my file. However, no change is made.

My file looks like this

            967 
      
              7
7836  783  273
              6

The output should be

              7
7836  783  273
              6

I have also tried to use tac filename | sed '/^$/I,+1 d' | tac', but I believe this does not work because my empty line might contain spaces or tabs. How could I achieve this? Thank you.

user19619903
  • 131
  • 5
  • 2
    What is the expected output if there are consecutive blank lines? – M. Nejat Aydin Mar 21 '23 at 19:49
  • You might be able to `diff` the output of your `grep` and your file. Something like `diff --changed-group-format='%<' --unchanged-group-format='' src.txt <(grep -B 1 -e '^[[:space:]]*$' src.txt)` – j_b Mar 21 '23 at 20:20
  • 3
    967 didn't become seven. The desired output is correct, based on what he is requesting. But it can be put in simpler words which would be easier to translate into code. "Remove lines with content that are followed by 'empty' lines with potential tabs or spaces. Including the 'empty' lines." – tenxsoydev Mar 21 '23 at 20:24

3 Answers3

2

if Your empty lines could contain spaces then
tac <fileName> | sed -E '/^\s*$/,+1 d' | tac

Yaser Kalali
  • 730
  • 1
  • 6
1

With :

In slurp mode: -0777 read the whole file in memory:

$ perl -0777 -pe 's/.*\n\s*\n//g' file

with Perl => 5.36:

$  perl -gpe 's/.*\n\s*\n//g' file

With GNU sed:

sed -rz 's/[^\n]*\n\s*\n//g' file

Output

              7
7836  783  273
              6
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
1

This might work for you (GNU sed):

sed 'N;/\n\s*$/d;/^\s*\n/!P;D' file

Open a two line window.

If the second line of the window is empty, delete both lines.

If the first line of the window is empty, don't print it.

Otherwise, print then delete the first line and repeat.

potong
  • 55,640
  • 6
  • 51
  • 83