Remove blank lines with grep

Viewed 327236

I tried grep -v '^$' in Linux and that didn't work. This file came from a Windows file system.

17 Answers

Do lines in the file have whitespace characters?

If so then

grep "\S" file.txt

Otherwise

grep . file.txt

Answer obtained from: https://serverfault.com/a/688789

This code removes blank lines and lines that start with "#"

 grep -v "^#" file.txt | grep -v ^[[:space:]]*$
awk 'NF' file-with-blank-lines > file-with-no-blank-lines

It's true that the use of grep -v -e '^$' can work, however it does not remove blank lines that have 1 or more spaces in them. I found the easiest and simplest answer for removing blank lines is the use of awk. The following is a modified a bit from the awk guys above:

awk 'NF' foo.txt

But since this question is for using grep I'm going to answer the following:

grep -v '^ *$' foo.txt

Note: the blank space between the ^ and *.

Or you can use the \s to represent blank space like this:

grep -v '^\s*$' foo.txt

Read lines from file exclude EMPTY Lines

grep -v '^$' folderlist.txt

folderlist.txt

folder1/test

folder2
folder3

folder4/backup
folder5/backup

Results will be:

folder1/test
folder2
folder3
folder4/backup
folder5/backup
Related