Saturday, December 20, 2014

Unix - Delete blank lines from file

Here's some ways to remove empty or blank lines from a file in Unix. Simple but definitely useful.
$ grep -v '^$' file.txt
$ grep '.' file.txt
$ sed '/^$/d' file.txt
$ sed -n '/^$/!p' file.txt
$ awk NF file.txt
$ awk '/./' file.txt

In Vi editor, in escape mode type
:g/^$/ d
Related posts:


Adithya Kiran said...

Another way..
$ grep . file.txt

Karan Bohra said...

sed '/./!d' file.txt

within the VI editor, we can do

Note that awk NF file.txt awk '/./' file.txt are not exactly equivalent.
awk NF will not print lines that have only space/TAB characters since the
field splitting by awk would ensure that they are canceled out. Whilst the
awk '/./' will print truly nonempty lines. We can also say:
awk 'length > 0' file.txt

perl -lne 'length&&print' file.txt

perl -lne '/./&&print' file.txt

sed -e 's/.*/[&]/' file.txt | dc -e "
[p]sp [q]sq
[? z 0 =q d Z 0 !=p c l?x]s?

while IFS= read -r line; do case $line in ?*) printf '%s\n' "$line";; esac; done < file.txt

cat file.txt | while IFS= read -r line; do
expr "$line" : '.*' 1>/dev/null && printf '%s\n' "$line"

© Jadu Saikia