Blank lines in generated lists, pasted configuration snippets, and command output can hide gaps that matter during review. sed can delete rows that are empty or contain only spaces or tabs while leaving the original nonblank rows in order.

On Linux, GNU sed treats \s as whitespace in a regular expression. The address /^\s*$/ matches a full line from start to end when every character is whitespace or when no characters are present, and pairing it with the d command tells sed to drop only those rows and print everything else.

Preview the cleaned output before overwriting a file. Redirecting to a new file keeps the source available for comparison and avoids platform-specific sed -i syntax, while a final grep -nP check should return no matching line numbers when the cleaned copy contains no empty or whitespace-only rows.

Steps to remove blank lines with sed:

  1. Prepare a source file that contains nonblank rows, empty rows, and any whitespace-only rows that should be removed.
    server01
    
    server02
       
    server03
  2. Preview the nonblank rows with sed without changing the file.
    $ sed '/^\s*$/d' servers.txt
    server01
    server02
    server03

    \s includes spaces and tabs in GNU sed, so the command removes whitespace-only lines as well as completely empty lines.

  3. Write the cleaned rows to a new file.
    $ sed '/^\s*$/d' servers.txt > servers-clean.txt
  4. Check the cleaned file for remaining blank or whitespace-only lines.
    $ grep -nP '^\s*$' servers-clean.txt

    No output means grep did not find any empty or whitespace-only rows.

  5. Review the cleaned file before using it or replacing the original file.
    $ cat servers-clean.txt
    server01
    server02
    server03