Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for empty lines in a file

Tags:

file

bash

unix

I don't have a code example here since I'm not sure how to do this at all, but I have a file. A legal empty line is one that only contains the new-line tab. Spaces or tabs are illegal.

How do I check if a line is "legally empty"?

If it doesn't have any words (I can check this with wc -w), how do I check if it has no spaces or tabs either, just new-line?

So I've tried something like this:

while read line; do
    if [[ "$line" =~ ^$ ]]; then
        echo empty line
        continue
    fi
done < $1

But it's not working. If I put a " " in an otherwise empty line, it still considers it empty.

like image 923
littlerunaway Avatar asked Dec 26 '13 13:12

littlerunaway


1 Answers

If you want the line numbers of those empty lines:

perl -lne 'print $. if(/^$/)' your_file

If you want to delete those lines without Perl:

grep . your_file >new_file

If you want to delete those empty line in place using Perl:

perl -i -lne 'print if(/./)' your_file
like image 180
Vijay Avatar answered Sep 21 '22 14:09

Vijay