Search code examples
linuxbashsedgreptac

Linux remove all empty lines and corresponding line above it


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.


Solution

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