【问题标题】:mistake in for loopfor循环中的错误
【发布时间】:2012-07-29 05:59:25
【问题描述】:

当我运行我的脚本时,我得到了这个错误:

234.sh: line 3: syntax error near unexpected token `do
234.sh: line 3: `for folder in $array ; do

我没有看到错误。帮忙?

#!/bin/bash
base=$(pwd)
array=`find * -type d`
 for folder in $array ; do
  cd $folder ;
  grep -n $1 * | while read line ;
   do    name=$(echo "$line" | cut -f1 -d:) ;
        if [ "$name" == "1234.sh" ]; then
        continue ;
        else
        string=$(echo "$line" | cut -f2 -d:) ;
        a=$(expr $string - 10)
        if [ $a -lt 1 ] ; then 
        a=1 ;
        fi ;
        b=$(expr $string + 10) ;   
        echo "-----------------------"
        echo $name:$a
        sed -n $a,${b}p $name;
        fi ;
    done
   cd $base ;
done

【问题讨论】:

  • 去掉';'在“do”之前并将“do”放在换行符上
  • 这不是必须的;用分号结束语句是合法的。
  • 你的名为“array”的变量不是一个数组,它是一个字符串。

标签: bash for-loop grep


【解决方案1】:
#!/bin/bash

base=$(pwd)
array=`find . -type d`
for folder in $array
do
  cd $folder
  grep -n $1 * | while read line
  do    
      name=$(echo "$line" | cut -f1 -d:)
      if [ "$name" == "1234.sh" ]
      then
        continue
      else
        string=$(echo "$line" | cut -f2 -d:)
        a=$(expr $string - 10)
        if [ $a -lt 1 ]
        then 
          a=1
        fi
        b=$(expr $string + 10)
        echo -----------------------
        echo $name:$a
        sed -n $a,${b}p $name
      fi
  done
  cd $base
done

【讨论】:

    【解决方案2】:

    一些建议:

    1. 使数组成为正确的数组,而不仅仅是字符串。 (这是唯一 实际解决您的语法错误的建议。)

    2. 报价参数

    3. 使用IFS 允许read 将您的行分成两个部分

    4. 使用子shell 消除cd $base 的需要。

    5. 大部分分号都是不必要的。


    #!/bin/bash
    array=( `find * -type d` )
    for folder in "${array[@]}" ; do
      ( cd $folder
        grep -n "$1" * | while IFS=: read fname count match; do
          [ "$fname" == "1234.sh" ] && continue
    
          a=$(expr $count - 10); [ $a -lt 1 ] && a=1
          b=$(expr $count + 10) 
          echo "-----------------------"
          echo $fname:$a
          sed -n $a,${b}p $fname
        done
      )
    done
    

    【讨论】:

      【解决方案3】:

      你想要完成的事情看起来像 目录树中所有文件上指定模式的上下文 grep。

      我建议你使用 Gnu grep Context Line Control

      #!/bin/bash
      base=$(pwd)
      spread=10
      pattern=$1
      
      find . -type d | while read dir; do
          (cd $dir && egrep -A $spread -B $spread $pattern *)
      done
      

      这是简单的版本,不处理1234.sh或空目录

      【讨论】:

        【解决方案4】:

        这个解决方案更简单,而且还处理豁免文件名。 这也取决于 xargs 和 Gnu grep Context Line Control

        #!/bin/bash
        spread=10
        pattern=$1
        
        find . -type f ! -name "1234.sh" |
            xargs egrep -A $spread -B $spread $pattern 
        

        【讨论】:

        • 如果演示很重要,这个解决方案还需要做更多的工作。
        猜你喜欢
        • 2016-08-15
        • 2018-08-04
        • 2011-10-23
        • 2011-06-21
        • 2016-07-27
        • 2018-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多