Remove blank lines with grep

2019-03-07 16:17发布

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

14条回答
Fickle 薄情
2楼-- · 2019-03-07 16:32

If you have sequences of multiple blank lines in a row, and would like only one blank line per sequence, try

grep -v "unwantedThing" foo.txt | cat -s

cat -s suppresses repeated empty output lines.

Your output would go from

match1



match2

to

match1

match2

The three blank lines in the original output would be compressed or "squeezed" into one blank line.

查看更多
Evening l夕情丶
3楼-- · 2019-03-07 16:32

Using Perl:

perl -ne 'print if /\S/'

\S means match non-blank characters.

查看更多
SAY GOODBYE
4楼-- · 2019-03-07 16:33

Same as above answers

grep -v -e '^$' foo.txt

Here, grep -e means extended version of grep. '^$' means that there is no character between ^(Start of line) and $(end of line). '^' and '$' are regex characters.

So the command grep -v will print all the lines that do not match this pattern (No characters between ^ and $).

This way empty blank lines are eliminated

查看更多
一纸荒年 Trace。
5楼-- · 2019-03-07 16:34

here is another way of removing the white lines and lines starting with # sign. I think this is quite useful to read configuration files.

[root@localhost ~]# cat /etc/sudoers | egrep -v '^(#|$)'
Defaults    requiretty
Defaults   !visiblepw
Defaults    always_set_home
Defaults    env_reset
Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR
LS_COLORS"
root    ALL=(ALL)       ALL
%wheel  ALL=(ALL)       ALL
stack ALL=(ALL) NOPASSWD: ALL
查看更多
姐就是有狂的资本
6楼-- · 2019-03-07 16:38

Try the following:

grep -v -e '^$' foo.txt

The -e option allows regex patterns for matching.

The single quotes around ^$ makes it work for Cshell. Other shells will be happy with either single or double quotes.

UPDATE: This works for me for a file with blank lines or "all white space" (such as windows lines with "\r\n" style line endings), whereas the above only removes files with blank lines and unix style line endings:

grep -v -e '^[[:space:]]*$' foo.txt
查看更多
女痞
7楼-- · 2019-03-07 16:41
$ dos2unix file 
$ grep -v "^$" file

Or just simply awk

awk 'NF' file

If you don't have dos2unix, then you can use tools like tr

tr -d '\r' < "$file" > t ; mv t "$file"
查看更多
登录 后发表回答