Delete blank lines from file

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

The following command only works for null strings, but not in the case of space:

sed '/^$/d' filename

Can this be done with grep?

+6
source share
4 answers

Use \s* for empty lines containing only spaces:

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

To save changes to a file, use the -i option:

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

Edit:

The regular expression ^\s*$ matches a line containing only spaces, grep -v print lines that do not match the given pattern, so the following will print all black lines:

  grep -v '^\s*$' file 
+12
source
 sed -i '/^[ \t]*$/d' file-name 

it will delete all empty lines that have any values. spaces (spaces or tabs), i.e. (0 or more) in the file.

NOte: there is a “space” in the square bracket followed by “\ t” ...

" -i " will force the updated contents to be written back to the file ... without this flag, you can see that empty lines were deleted on the screen, but the actual file will not be affected.

+1
source

The portable POSIX way to do this is

 sed -i '/^[[:blank:]]*$/d' file 

or

 grep -v '^[[:blank:]]*$' file 
+1
source

It so happened that the file was copied from a Windows computer, the sed command (sed '/ ^ $ / d' foo) was not run correctly.

I ran the following command and it worked.

$ dos2unix foo

0
source

All Articles