Checking empty lines in a file

I have no sample code, since I'm not sure how to do this at all, but I have a file. The left blank line is the one that contains only the new line tab. Spaces or tabs are illegal.

How to check if the string is "legally empty"?

If it has no words (I can check it with wc -w), how can I check if it has spaces or tabs, just a new line?

So, I tried something like this:

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

But it does not work. If I put "" in an empty string otherwise, it still considers it empty.

+1
source share
3 answers

If you need the line numbers of these empty lines:

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

Perl:

grep . your_file >new_file

Perl:

perl -i -lne 'print if(/./)' your_file
+3

: , , . , ( ), .

read . , , , . , ( , ): IFS . . while IFS= read , IFS=; while read..? . , -r read, , .

while IFS= read -r line; do
  if [ -z "$line" ]; then
    echo empty line
  fi
done <"$1"

, :

while IFS= read -r line; do
  case "$line" in
    '') echo "empty line";;
    *[![:space:]]*) echo "non-blank line";;
    *) echo "non-empty blank line";;
  esac
done <"$1"

Bash , :

while IFS= read -r line; do
  if [[ "$line" =~ ^$ ]]; then
     echo "empty line"
  elif [[ "$line" =~ ^[[:space:]]+$ ]]; then
    echo "non-empty blank line"
  else
    echo "non-blank line"
  fi
done <"$1"

( , ):

while IFS= read -r line; do
  if [[ "$line" == "" ]]; then
     echo "empty line"
  elif [[ "$line" != *[![:space:]]* ]]; then
    echo "non-empty blank line"
  else
    echo "non-blank line"
  fi
done <"$1"

- , grep:

if grep -qxF '' <"$1"; then
  echo "$1 contains an empty line"
fi

, :

if grep -Ex '[[:space:]]+' <"$1"; then
  echo "$1 contains a non-empty blank line"
fi
+2

^$

^ - , $ - , , .

, .

sed '/^$/d' input.txt

. . .

( ), :

sed -i '/^$/d' input.txt
0

Source: https://habr.com/ru/post/1676535/


All Articles