Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete empty lines using sed

Tags:

linux

unix

sed

I am trying to delete empty lines using sed:

sed '/^$/d' 

but I have no luck with it.

For example, I have these lines:

xxxxxx   yyyyyy   zzzzzz 

and I want it to be like:

xxxxxx yyyyyy zzzzzz 

What should be the code for this?

like image 774
jonas Avatar asked May 07 '13 08:05

jonas


People also ask

How do you delete a line in a file using sed?

To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.

How do I remove blank lines from awk?

We can remove blank lines using awk: $ awk NF < myfile.


1 Answers

You may have spaces or tabs in your "empty" line. Use POSIX classes with sed to remove all lines containing only whitespace:

sed '/^[[:space:]]*$/d' 

A shorter version that uses ERE, for example with gnu sed:

sed -r '/^\s*$/d' 

(Note that sed does NOT support PCRE.)

like image 126
Kent Avatar answered Sep 18 '22 15:09

Kent