176

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
kenorb
  • 7,125

10 Answers10

209

This sed line should do the trick:

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

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

Eddie C.
  • 549
  • 1
  • 3
  • 12
128

grep

Simple solution is by using grep (GNU or BSD) command as below.

  • Remove blank lines (not including lines with spaces).

    grep . file.txt
    
  • Remove completely blank lines (including lines with spaces).

    grep "\S" file.txt
    

Note: If you get unwanted colors, that means your grep is aliases to grep --color=auto (check by type grep). In that case, you can add --color=none parameter, or just run the command as \grep (which ignores the alias).


ripgrep

Similar with ripgrep (suitable for much larger files).

Remove blank lines not including lines with spaces:

rg -N . file.txt

or including lines with spaces:

rg -N "\S" file.txt

See also:

kenorb
  • 7,125
39
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.

Kamil Kisiel
  • 12,444
23

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

Like this

grep -Ev "^$" file.txt
jdabney
  • 331
22

Here is an awk solution:

awk NF file.txt

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

kenorb
  • 7,125
Zombo
  • 1
10

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

cat file.txt | tr -s '\n' '\n'
siddhadev
  • 201
2

xargs if you dont mind stripping leading whitespace

$ docker run -it --rm alpine sh
/ # cat <<eof > /tmp/file
> one
>
>   two
> three
>
>
>   four
> eof
/ # cat /tmp/file
one

  two
three


  four
/ # cat /tmp/file | xargs -n1
one
two
three
four
1

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
kenorb
  • 7,125
1

For me @martigin-heemels command was throwing error this fixed it (ie a dummy param to i),

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

0

The simplest solution I have ever found:

cat file.txt | strings