How to remove empty/blank lines from a file in Unix (including spaces)?
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
Solution 1:
This sed line should do the trick:
sed -i '/^$/d' file.txt
The -i
means it will edit the file in-place.
Solution 2:
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:
- How to remove blank lines from a file (including tab and spaces)?
- With
sed
: Delete empty lines using sed - With
awk
: Remove blank lines using awk
Solution 3:
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.