我有一个如下所示的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
bash:
if [[ ! $line =~ [^[:space:]] ]] ; then
continue
fi
请使用done < file
而不是cat file | while
,除非你知道为什么要使用后者。
while read
循环中,如果你想要跳过空行或者至少包含一个空格的行,那么cat
在这种情况下是无用的。
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
awk 'NF' file | while read line
do
# run some commands using $line
done
从类似的问题中窃取了这个答案: 使用sed删除空行
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
read
使用的定界符由IFS
变量确定,默认为空格。只需取消设置IFS
以恢复使用空格作为定界符即可。 - Arkku[[ -z $line ]] && continue
。 - pihentagy[]
在某些国际键盘上比引号更难打,而且它只能在 Bash 中使用。所以说这并不一定更简单,但可以作为一个替代方案。=) - Arkku[ -z "$line" ] && continue
这一行本身就是可执行的。这个简洁的语句等同于if [ -z "$line" ] ; then continue ; fi
。另外,不要忘记在开头设置IFS=" \t\n"
,除非您不想跳过制表符。 - Xin Cheng