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
This sed line should do the trick:
The
-i
means it will edit the file in-place.grep
Simple solution is by using
grep
(GNU or BSD) command as below.Remove blank lines (not including lines with spaces).
Remove completely blank lines (including lines with spaces).
Note: If you get unwanted colors, that means your
grep
is aliases togrep --color=auto
(check bytype 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:
or including lines with spaces:
See also:
sed
: Delete empty lines using sedawk
: Remove blank lines using awkd 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.You can use the -v option with grep to remove the matching empty lines.
Like this
Here is an
awk
solution:With Awk,
NF
only set on non-blank lines. When this condition match, Awk default action is to print the whole line.To remove empty lines, you could squeeze new line repeats with
tr
:Ex/Vim
Here is the method using
ex
editor (part of Vim):For multiple files (edit in-place):
Note: The
:bufdo
command is not POSIX.Without modifying the file (just print on the standard output):
xargs if you dont mind stripping leading whitespace
For me @martigin-heemels command was throwing error this fixed it (ie a dummy param to i),
sed -i '' '/^$/d' file.txt