Skip blank lines when iterating through file line by line

61,646

Solution 1

Remove the blank lines first with sed.

for word in `sed '/^$/d' $inputfile`; do
    myarray[$index]="$word"
    index=$(($index+1))
done

Solution 2

Be more elegant:

echo "\na\nb\n\nc" | grep -v "^$"

cat $file | grep -v "^$" | next transformations...

Solution 3

Implement the same test as in your pseudo-code:

while read line; do
    if [ ! -z "$line" ]; then
        myarray[$index]="$line"
        index=$(($index+1))
    fi
done < $inputfile

The -z test means true if empty. ! negates (i.e. true if not empty).

You can also use expressions like [ "x$line" = x ] or test "x$line" = x to test if the line is empty.

However, any line which contains whitespace will not be considered empty. If that is a problem, you can use sed to remove such lines from the input (including empty lines), before they are passed to the while loop, as in:

sed '/^[ \t]*$/d' $inputfile | while read line; do
    myarray[$index]="$line"
    index=$(($index+1))
done

Solution 4

cat -b -s file |grep -v '^$'

I know it's solved but, I needed to output numbered lines while ignoring empty lines, so I thought of putting it right here in case someone needs it. :)

Solution 5

Use grep to remove the blank lines:

for word in $(cat ${inputfile} | grep -v "^$"); do
   myarray[$index]="${word}"
   index=$(($index+1))
done
Share:
61,646
MAXGEN
Author by

MAXGEN

Updated on July 20, 2021

Comments

  • MAXGEN
    MAXGEN almost 3 years

    I am iterating through a file line by line and put each word into a array and that works. But it also picks up blank lines and puts it as an item in the array, how can I skip the blank lines?

    example file

          Line 1
    line 2
    
    line 3
            line 4 
    
    line 5
       line 6
    

    My code

    while read line ; do
                myarray[$index]="$line"
                index=$(($index+1))
        done < $inputfile
    

    Possible psuedo code

    while read line ; do
               if (line != space);then
                myarray[$index]="$line"
                 fi
                index=$(($index+1))
        done < $inputfile