I have a file (hosts) with some lines without content, how do I remove that lines without content?
5 Answers
Using sed
Type the following command:
sed '/^$/d' input.txt > output.txt
Using grep
Type the following command:
grep -v '^$' input.txt > output.txt
Many ways:
Use
sed
and edit the file in place.sudo sed -i -rn '/\S/p' /etc/hosts
Same, but with Perl:
sudo perl -i -ne 'print if /\S/' /etc/hosts
Newer versions of GNU
awk
, in place again:sudo awk -i inplace '/\S/' file
All of the above solutions will also remove lines that contain nothing but whitespace. If you only want to remove empty lines, and leave lines that contain spaces or tabs etc, change the /\S/
to /^$/
in all of the above examples.
Sometimes the other commands will fail to remove blank lines if the lines contain a blank space. The following will remove all blank lines including lines that contain only blank spaces.
grep -v '^[[:space:]]*$' input.txt > output.txt
-
Is a nice solutions, in xml files for example is possible to have spaces. A similar solution with sed can be: "sed '/^\s*$/d' input.txt > output.txt" Nov 16, 2022 at 19:58
You can use Vim in Ex mode:
ex -sc v/./d -cx hosts
/./
find non blank linesv
invert selectiond
deletex
save and close
You can do this in the default Ubuntu Text Editor (gedit) by:
- Press
Ctrl
+H
to open Find and Replace - In the 'Find' box, enter
\n\n
which signifies two new lines without text in-between them. - In the 'Replace' box, enter
\n
- Click 'Replace All'
If the text file was produced in windows, you may want to try \r\n
.