37

我有一个这样的shell脚本:

cat file | while read line
do
    # run some commands using $line    
done

现在我需要检查该行是否包含任何非空白字符([\n\t]),如果没有,请跳过它。我怎样才能做到这一点?

4

7 回答 7

80

由于read默认情况下读取以空格分隔的字段,因此仅包含空格的行应导致将空字符串分配给变量,因此您应该能够跳过空行,只需:

[ -z "$line" ] && continue
于 2010-04-05T12:16:22.867 回答
16

试试这个

while read line;
do 

    if [ "$line" != "" ]; then
        # Do something here
    fi

done < $SOURCE_FILE
于 2012-10-16T18:23:39.860 回答
6

重击:

if [[ ! $line =~ [^[:space:]] ]] ; then
  continue
fi

并使用done < file而不是cat file | while,除非您知道为什么要使用后者。

于 2010-04-05T11:38:46.310 回答
2

cat在这种情况下,如果您使用的是 while read 循环,我将毫无用处。我不确定您的意思是要跳过空行还是要跳过至少也包含空格的行。

i=0
while read -r line
do
  ((i++)) # or $(echo $i+1|bc) with sh
  case "$line" in
    "") echo "blank line at line: $i ";;
    *" "*) echo "line with blanks at $i";;
    *[[:blank:]]*) echo "line with blanks at $i";;
  esac
done <"file"
于 2010-04-05T12:33:16.170 回答
1
if ! grep -q '[^[:space:]]' ; then
  continue
fi
于 2010-04-05T11:47:41.313 回答
0
blank=`tail -1 <file-location>`
if [ -z "$blank"  ]
then
echo "end of the line is the blank line"
else
echo "their is something in last line"
fi
于 2019-09-06T06:09:16.157 回答
0
awk 'NF' file | while read line
do
    # run some commands using $line    
done

偷了一个类似问题的答案: Delete empty lines using sed

于 2022-01-15T13:49:02.103 回答