45

How do I remove empty/blank (including spaces only) lines in a file in Unix/Linux using the command line?

contents of file.txt

Line:Text
1:<blank>
2:AAA
3:<blank>
4:BBB
5:<blank>
6:<space><space><space>CCC
7:<space><space>
8:DDD

output desired

1:AAA
2:BBB
3:<space><space><space>CCC
4:DDD
76

This sed line should do the trick:

sed -i '/^$/d' file.txt

The -i means it will edit the file in-place.

26
sed '/^$/d' file.txt

d is the sed command to delete a line. ^$ is a regular expression matching only a blank line, a line start followed by a line end.

22

Simple solution by using grep (GNU or BSD) command:

grep . file

Similar with ripgrep (suitable for much larger files):

rg -N . file
  • 2
    grep . seems to be the simplest solution. – Leo Mar 21 '18 at 21:36
18

You can use the -v option with grep to remove the matching empty lines.

Like this

grep -Ev "^$" file.txt
  • 3
    I don't believe you need the -E, at least not with GNU grep, but apart from that I'm so pleased to see this done with grep! It's what I reach for in preference to sed, every time; in-line filters seem to me to be better than in-line editors. – MadHatter Mar 28 '11 at 22:45
  • If you want to skip the commented and blank lines, especially while dealing with conf files use grep -Ev '^#|^$' file.txt – Govind Kailas Mar 7 at 4:11
6

To remove empty lines, you could squeeze new line repeats with tr:

cat file.txt | tr -s '\n' '\n'
1

Here is an awk solution:

awk NF file

With Awk, NF only set on non-blank lines. When this condition match, Awk default action is to print the whole line.

0

Ex/Vim

Here is the method using ex editor (part of Vim):

ex -s +'v/\S/d' -cwq test.txt

For multiple files (edit in-place):

ex -s +'bufdo!v/\S/d' -cxa *.txt

Note: The :bufdo command is not POSIX.

Without modifying the file (just print on the standard output):

cat test.txt | ex -s +'v/\S/d' +%p +q! /dev/stdin

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.