To remove blank lines in data set

2019-05-06 22:56发布

问题:

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.

回答1:

it can be done in many ways.

e.g with awk:

awk '$0' yourFile

or sed:

sed '/^$/d' yourFile

or grep:

grep -v '^$' yourFile


回答2:

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.



回答3:

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


回答4:

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



回答5:

You can do:

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


回答6:

A Perl solution:

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

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



标签: perl shell sed awk