【问题标题】:How can I test if line is empty in shell script?如何测试 shell 脚本中的行是否为空?
【发布时间】:2011-02-04 09:46:39
【问题描述】:

我有一个这样的 shell 脚本:

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

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

【问题讨论】:

    标签: bash shell sh


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案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"
      

      【讨论】:

        【解决方案3】:

        试试这个

        while read line;
        do 
        
            if [ "$line" != "" ]; then
                # Do something here
            fi
        
        done < $SOURCE_FILE
        

        【讨论】:

        • 更多关于方括号符号的信息可以在the man page of test找到
        • 这里的缺点:如果 if 中的部分很长,您会得到一个难以阅读的代码。因此,始终建议使用 continue 解决方案。
        【解决方案4】:

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

        [ -z "$line" ] && continue
        

        【讨论】:

        • (更准确地说,read 使用的分隔符由 IFS 变量确定,默认为空格。只需取消设置 IFS 即可恢复使用空格。)
        • 更简单:不需要引用行,如果你使用 bash 的 [[ 语法:[[ -z $line ]] &amp;&amp; continue
        • @pihentagy Umm,具有相同数量的字符,方括号[] 在某些国际键盘上比引号更难键入,并且它变得特定于 bash。所以也许不是更简单,而是另一种选择。 =)
        • (适合像我这样的新手)。 [ -z "$line" ] &amp;&amp; continue 本身是可执行的。这条优雅的线相当于if [ -z "$line" ] ; then continue ; fi。顺便说一句,除非你不想跳过'tab',否则不要忘记在开头设置IFS=" \t\n"
        • 重新。建议的添加内容的编辑,请改为发布您自己的答案 - 这可以按原样回答原始问题,并且无论外壳如何都可以通用,因此我认为通过将其与特定外壳的更多案例复杂化并不会改善答案和/或超出原始问题的需求
        【解决方案5】:
        if ! grep -q '[^[:space:]]' ; then
          continue
        fi
        

        【讨论】:

          【解决方案6】:

          重击:

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

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

          【讨论】:

          • 我需要在 bash 和 sh 中都可以使用的东西。有没有使用 sh/sed/tr 的解决方案(如果没有安装 bash)?
          • 这行得通,另一个 ([ -z "$line" ] && continue) 不行。我想知道为什么。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-29
          • 1970-01-01
          • 2013-03-06
          • 1970-01-01
          相关资源
          最近更新 更多