Search code examples
unixsedgrep

Delete empty lines from a file


I need to delete empty lines from a file (with spaces only - not null records).

The following command works only for null rows, but not in case of spaces:

sed '/^$/d' filename

Can it be done using grep?


Solution

  • Use \s* for blank lines containing only whitespace:

    sed '/^\s*$/d' file 
    

    To save the changes back to the file use the -i option:

    sed -i '/^\s*$/d' file 
    

    Edit:

    The regex ^\s*$ matches a line that only contains whitespace, grep -v print lines that don't match a given pattern so the following will print all none black lines:

    grep -v '^\s*$' file