Linux remove all empty lines and corresponding line above it

125 views Asked by At

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.

3

There are 3 answers

0
Yaser Kalali On BEST ANSWER

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

3
Gilles Quénot On

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
1
potong On

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.