2012-07-31 134 views
3

当我运行我的剧本我得到这个错误:错误在for循环

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 
+0

删除';'在'做'之前并在换行符上放上'do' – Les 2012-07-31 13:00:50

+1

这应该不是必需的;用分号结束语句是合法的。 – chepner 2012-07-31 13:09:20

+2

名为“数组”的变量不是数组,它是一个字符串。 – jordanm 2012-07-31 13:12:42

回答

3

几点建议:

  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 
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 
1

你要完成的样子 上下文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或空目录

1

该解决方案甚至不太复杂,并与另外的交易免除文件名称。 它也取决于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 
+0

如果演示文稿非常重要,则需要更多工作来解决此问题。 – 2012-08-01 11:31:22