2015-11-16 195 views
-3

我试图实现一个简单的shell程序,显示文件中包含的法国电话号码。逻辑或| Unix

这里是我的基本壳

#!/bin/bash 

#search of phone numbers 

t=(\+ | 00)33[1-9][0-9]{8} 
t2=(\+ | 00)33[1-9][0-9]-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2} 
t3=(\+ | 00)33[1-9][0-9].[0-9]{2}.[0-9]{2}.[0-9]{2}.[0-9]{2} 

grep -e $1 ($t | $t2 | $t3) 

这里是我的输入文件:

phone_number.txt

+33143730862 

00335.45.45.45.45 

+332-45-45-45-45 

+334545454554454545 

我不断收到此错误:

./script_exo2.sh: line 5: syntax error near unexpected token `|' 
./script_exo2.sh: line 5: `t=(\+ | 00)33[1-9][0-9]{8}' 
./script_exo2.sh: line 6: syntax error near unexpected token `|' 
./script_exo2.sh: line 6: `t2=(\+ | 00)33[1-9][0-9]-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}' 
./script_exo2.sh: line 7: syntax error near unexpected token `|' 
./script_exo2.sh: line 7: `t3=(\+ | 00)33[1-9][0-9].[0-9]{2}.[0-9]{2}.[0-9]{2}.[0-9]{2}' 
./script_exo2.sh: line 9: syntax error near unexpected token `(' 
./script_exo2.sh: line 9: `grep -e $1 ($t | $t2 | $t3)' 
+10

你可能想要在字符串和变量之间加一些引号。 http://www.shellcheck.net是你的朋友。 – Biffen

+4

OS X上的'bash'与任何你能找到的Linux上的'bash'都一样。您提供的脚本在任何脚本中都是无效的,因为它使用shell元字符和控制操作符在需要将它们作为数据(特别是'(',')','''和空格字符)。 –

+0

'00'不是一个通用的国际通话前缀,但在许多国家都是正确的。这就是为什么我们需要普遍的'+'。 – tripleee

回答

3

您的t2t3比您尝试匹配的样本多一位数字。此外,您还需要引用的论据,并摆脱那些空间:

#!/bin/sh 
t='(\+|00)33[1-9][0-9]{8}' 
t2='(\+|00)33[1-9]-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}' 
t3='(\+|00)33[1-9]\.[0-9]{2}\.[0-9]{2}\.[0-9]{2}\.[0-9]{2}' 

exec grep -E -e "$t|$t2|$t3" "[email protected]" 
  1. 我用sh代替bash,因为我们不使用任何bash特性不提供标准的POSIX壳(例如dash)。
  2. 我对tt1t2的定义使用了上面的单引号,并且使用双引号将它们替换。
  3. 我已经通过-E标志告诉grep了解扩展正则表达式,并且我已将该模式作为参数-e(“表达式”)标志设置为grep
  4. grep进程exec代替shell,因为没有理由为此分支。
  5. 我已经通过了全套的输入参数"[email protected]"这样你就可以给额外的选项来grep(如-w-n-o,例如),并选择是否提供文件或流标准输入到你的脚本。

还要注意的是,如果你愿意接受的.-或没有分离数字对混合,可以简化你的三个表达式只有一个:

(\+|00)33[1-9][0-9]([-.]?[0-9]{2}){4} 

和脚本变得

#!/bin/bash 
exec grep -E -e '(\+|00)33[1-9]([-.]?[0-9]{2}){4}' "[email protected]" 

如果需要分隔符匹配,那么你可以使用一个捕获组为:

#!/bin/bash 
exec grep -E -e '(\+|00)33[1-9]([-.]?)[0-9]{2}(\2[0-9]{2}){3}' "[email protected]" 
+0

非常感谢您的帮助。 –