Linux Tips and Tricks

Linux Tips and Tricks

Remove empty lines from file

September12

Lets say we have two empty lines in the file (blank_lines.txt)

1
2
3
4
5
6
$ cat -n blank_lines.txt
     1    this is test file
     2
     3    for blank lines
     4
     5    we have two blank lines in this file

Using grep

1
2
3
4
$ grep . blank_lines.txt
this is test file
for blank lines
we have two blank lines in this file

using awk

1
2
3
4
$ awk '/./ {print}' blank_lines.txt
this is test file
for blank lines
we have two blank lines in this file
1
2
3
4
s$ awk '!/^$/ {print}'  blank_lines.txt
this is test file
for blank lines
we have two blank lines in this file

using sed

1
2
3
4
$ sed '/^$/d' blank_lines.txt
this is test file
for blank lines
we have two blank lines in this file

using perl

1
2
3
4
$ perl -lane 'print $_ if($_=~/./)' blank_lines.txt
this is test file
for blank lines
we have two blank lines in this file
1
2
3
4
5
6
$ perl -pi -e "s/^\n//" blank_lines.txt
 
$ cat blank_lines.txt
this is test file
for blank lines
we have two blank lines in this file
1
2
3
4
$ perl -lane 'print $_ if($_!~m/^$/)' blank_lines.txt
this is test file
for blank lines
we have two blank lines in this file
1
2
3
4
$ perl -lane 'print $_ if($_ ne "")' blank_lines.txt
this is test file
for blank lines
we have two blank lines in this file

Note : If your blank line contains the spaces, then you need to use /^\s*$/

posted under Uncategorized

Email will not be published

Website example

Your Comment:


Recent Comments

    Categories