【发布时间】:2011-02-04 09:46:39
【问题描述】:
我有一个这样的 shell 脚本:
cat file | while read line
do
# run some commands using $line
done
现在我需要检查该行是否包含任何非空白字符([\n\t]),如果没有,请跳过它。 我该怎么做?
【问题讨论】:
我有一个这样的 shell 脚本:
cat file | while read line
do
# run some commands using $line
done
现在我需要检查该行是否包含任何非空白字符([\n\t]),如果没有,请跳过它。 我该怎么做?
【问题讨论】:
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
【讨论】:
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"
【讨论】:
试试这个
while read line;
do
if [ "$line" != "" ]; then
# Do something here
fi
done < $SOURCE_FILE
【讨论】:
由于read 默认读取以空格分隔的字段,因此仅包含空格的行应导致将空字符串分配给变量,因此您应该能够跳过空行:
[ -z "$line" ] && continue
【讨论】:
read 使用的分隔符由 IFS 变量确定,默认为空格。只需取消设置 IFS 即可恢复使用空格。)
[[ -z $line ]] && continue
[] 在某些国际键盘上比引号更难键入,并且它变得特定于 bash。所以也许不是更简单,而是另一种选择。 =)
[ -z "$line" ] && continue 本身是可执行的。这条优雅的线相当于if [ -z "$line" ] ; then continue ; fi。顺便说一句,除非你不想跳过'tab',否则不要忘记在开头设置IFS=" \t\n"。
if ! grep -q '[^[:space:]]' ; then
continue
fi
【讨论】:
重击:
if [[ ! $line =~ [^[:space:]] ]] ; then
continue
fi
并使用done < file 而不是cat file | while,除非您知道为什么要使用后者。
【讨论】: