Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete empty lines from a file

Tags:

grep

unix

sed

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?

like image 284
v_b Avatar asked Dec 20 '12 10:12

v_b


People also ask

How do I mass delete blank lines in Word?

To start removing empty lines, open your document with Microsoft Word. Click “Home” in the menu and then select “Replace” on the right of the screen. Then click “Replace All” at the bottom of the window. After you click, all the blank lines will be removed from your document.


2 Answers

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
like image 70
Chris Seymour Avatar answered Sep 30 '22 12:09

Chris Seymour


The POSIX portable way to do this is

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

or

grep -v '^[[:blank:]]*$' file
like image 43
Jens Avatar answered Sep 30 '22 10:09

Jens