v_b
v_b

Reputation: 225

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?

Upvotes: 12

Views: 43673

Answers (4)

Garfield Carneiro
Garfield Carneiro

Reputation: 1

It happened that the file was copied from Windows machine a the sed command (sed '/^$/d' foo) was not running correctly.

I ran following command and it worked.

$ dos2unix foo

Upvotes: 0

Prabhat Kumar Singh
Prabhat Kumar Singh

Reputation: 1809

sed -i '/^[ \t]*$/d' file-name

it will delete all blank lines having any no. of white spaces (spaces or tabs) i.e. (0 or more) in the file..

Note: there is a 'space' followed by '\t' inside the square bracket...

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

Upvotes: 1

Jens
Jens

Reputation: 72756

The POSIX portable way to do this is

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

or

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

Upvotes: 4

Chris Seymour
Chris Seymour

Reputation: 85883

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

Upvotes: 21

Related Questions