无法跳过shell脚本中的空白行

时间:2018-05-04 05:00:04

标签: bash shell sh

我正在逐行阅读文本文件,并将所有行的计数作为我要求的一部分。

当有空行时,它会搞砸。我尝试使用[ -z "$line" ]的if条件,但无法成功。

这是我目前的代码:

countNumberOfCases() {
echo "2.  Counting number of test cases -----------"
    cd $SCRIPT_EXECUTION_DIR
    FILE_NAME=Features
    while read line || [[ -n "$line" ]]
    do
        TEST_CASE="$line"                       
        if [ "${TEST_CASE:0:1}" != "#" ] ; then
            cd $MVN_EXECUTION_DIR
                runTestCase     
        fi
    done < $FILE_NAME

    echo " v_ToalNoOfCases : = " $v_ToalNoOfCases
}

以下是功能文件

web/sprintTwo/TC_002_MultipleLoginScenario.feature
#web/sprintOne/TC_001_SendMoneyTransaction_Spec.feature

web/sprintTwo/TC_003_MultipleLoginScenario.feature
#web/sprintOne/TC_004_SendMoneyTransaction_Spec.feature

当有空白行时它不会正常工作所以我的要求是如果有空行则应该跳过它,不应该考虑。

1 个答案:

答案 0 :(得分:1)

你可以用更健壮的方式编写循环:

#!/bin/bash

while read -r line || [[ $line ]]; do                                 # read lines one by one
  cd "$mvn_execution_dir" # make sure this is an absolute path
                          # or move it outside the loop unless "runTestCase" function changes the current directory
  runTestCase "$line"     # need to pass the argument?
done < <(sed -E '/^[[:blank:]]*$/d; /^[[:blank:]]+#/d' "$file_name")  # strip blanks and comments

一些事情: