bash回到grep循环,如果然后失踪'

时间:2014-10-31 22:26:54

标签: linux bash if-statement grep

我的Syst管理员刚刚开始教我们bash,他希望我们用grep编写一个bash脚本,在linux字典中查找所有3-45个字母的文字而不使用反向。我在if语句中收到错误,说我错过了'

更新代码:

    front='\([a-z]\)'
front_s='\([a-z]\)'
numcheck=1
back='\1'
middle='[a-z]'
count=3

while [ $count -ne "45" ]; do

    if [[ $(($count % 2)) == 0 ]]
        then
            front=$front$front_s
            back=+"\\$numcheck$back"
            grep "^$front$back$" /usr/share/dict/words
            count=$((count+1))
        else
            grep "^$front$middle$back$" /usr/share/dict/words

            numcheck=$((numcheck+1))
            count=$((count+1))
    fi

done

2 个答案:

答案 0 :(得分:1)

这里有四个明显的问题:

  • 首先是关于错位和未转义的反斜杠:

    back="\\$numcheck$back" # and not back="$numcheck\$back"
    
  • 其次,如果numcheck为奇数,您只想增加count
  • 第三:在行

     front=$front$front
    

    加倍 front中的模式数量!嘿,这会产生指数增长,因此爆炸参数列表太长。要解决此问题:添加一个变量,例如front_step

    front_step='\([a-z]\)'
    front=$front_step
    

    当你增加front时:

    front=$front$front_step
    

修好后,你应该好!

第四个缺陷是grep的反向引用可能只有一位数:来自man grep

Back References and Subexpressions
   The back-reference \n, where n is a single digit, matches the substring
   previously  matched  by  the  nth  parenthesized  subexpression  of the
   regular expression.

在您的方法中,我们最多需要22个反向引用。这对grep来说太过分了。我怀疑有没有这么长的回文。

另外,你正在把文件砸了43次......这有点太多了。

答案 1 :(得分:0)

试试这个:

#!/bin/bash

 for w in `grep -E "^[[:alnum:]]{3,45}$" /usr/share/dict/words`; do if [[ "$w" == "`echo $w|sed "s/\(.\)/\1\n/g"|tac|tr -d '\012'`" ]]; then echo "$w == is a palindrome"; fi; done

OR

#!/bin/bash

front='\([a-z]\)'
numcheck=1
back='\1'
middle='[a-z]'
count=3

while [ $count -ne "45" ]; do

    if [[ $(($count % 2)) == 0 ]]
        then
            front=$front$front
            back="\\$numcheck$back"
            grep "^$front$back$" /usr/share/dict/words
        else
            grep "^$front$middle$back$" /usr/share/dict/words

            ## Thanks to gniourf for catching this.
            numcheck=$((numcheck+1))
    fi

    count=$((count+1))
    ## Uncomment the following if you want to see one by one and run script using bash -x filename.sh
    #echo Press any key to continue: ; read toratora;

done