我有一个这样的shell脚本:
cat file | while read line
do
# run some commands using $line
done
现在我需要检查该行是否包含任何非空白字符([\n\t]),如果没有,请跳过它。我怎样才能做到这一点?
由于read
默认情况下读取以空格分隔的字段,因此仅包含空格的行应导致将空字符串分配给变量,因此您应该能够跳过空行,只需:
[ -z "$line" ] && continue
试试这个
while read line;
do
if [ "$line" != "" ]; then
# Do something here
fi
done < $SOURCE_FILE
重击:
if [[ ! $line =~ [^[:space:]] ]] ; then
continue
fi
并使用done < file
而不是cat file | while
,除非您知道为什么要使用后者。
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"
if ! grep -q '[^[:space:]]' ; then
continue
fi
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
awk 'NF' file | while read line
do
# run some commands using $line
done
偷了一个类似问题的答案: Delete empty lines using sed