Angelo
Angelo

Reputation: 5059

To remove blank lines in data set

I need a one liner using sed, awk or perl to remove blank lines from my data file. The data in my file looks like this -

Aamir
Ravi 

Arun


Rampaul
Pankaj

Amit

Bianca

These blanks are at random and appear anywhere in my data file. Can someone suggest a one-liner to remove these blank lines from my dataset.

Upvotes: 4

Views: 7433

Answers (6)

Bharatt
Bharatt

Reputation: 19

for perl it is as easier as sed,awk, or grep.

$ cat tmp/tmpfile
Aamir
Ravi

Arun


Rampaul
Pankaj

Amit

Bianca

$ perl -i -pe 's{^\s*\n$}{}' tmp/tmpfile

$ cat tmp/tmpfile
Aamir
Ravi
Arun
Rampaul
Pankaj
Amit
Bianca

Upvotes: 1

JRFerguson
JRFerguson

Reputation: 7526

A Perl solution:

perl -ni.old -e 'print unless /^\s*$/' file

...which create as backup copy of the original file, suffixed with '.old'

Upvotes: 1

Dave Cross
Dave Cross

Reputation: 69314

A Perl solution. From the command line.

$ perl -i.bak -n -e'print if /\S/' INPUT_FILE

Edits the file in-place and creates a backup of the original file.

Upvotes: 6

jaypal singh
jaypal singh

Reputation: 77155

AWK Solution:

Here we loop through the input file to check if they have any field set. NF is AWK's in-built variable that is set to th number of fields. If the line is empty then NF is not set. In this one liner we test if NF is true, i.e set to a value. If it is then we print the line, which is implicit in AWK when the pattern is true.

awk 'NF' INPUT_FILE

SED Solution:

This solution is similar to the ones mentioned as the answer. As the syntax show we are not printing any lines that are blank.

sed -n '/^$/!p' INPUT_FILE

Upvotes: 3

codaddict
codaddict

Reputation: 455342

You can do:

 sed -i.bak '/^$/d' file

Upvotes: 2

Kent
Kent

Reputation: 195209

it can be done in many ways.

e.g with awk:

awk '$0' yourFile

or sed:

sed '/^$/d' yourFile

or grep:

grep -v '^$' yourFile

Upvotes: 7

Related Questions