Bash: reading a line and saving spaces

I am trying to read lines from a file containing multiple lines. I want to identify lines containing only spaces. By definition, an empty string is empty and contains nothing (including spaces). I want to detect lines that seem empty but they are not (lines containing only spaces)

    while read line; do
        if [[ `echo "$line" | wc -w` == 0 && `echo "$line" | wc -c` > 1 ]];
        then
             echo "Fake empty line detected"
        fi
    done < "$1"

But since reading ignores spaces at the beginning and end of the line, my code does not work.

file example

hi
 hi
(empty line, no spaces or any other char)
hi
  (two spaces)
hey

Please help me fix the code

+4
source share
2 answers

Disable word splitting by clearing the IFS value (internal field separator):

while IFS= read -r line; do
....
done < "$1"

-r not strictly necessary, but it is good practice.


, line ( , , ):

if [[ $line =~ ^$ ]]; then
    echo "Fake empty line detected"
fi
+7

, .

while read line; do
        if [ -z "$line" ]
        then
             echo "Fake empty line detected"
        fi
done < "$1"

-z , $line .

:

Fake empty line detected
Fake empty line detected
+1

All Articles